I have a div and when a user clicks on it using the onclick
event, i'm calling a function:
function test(a)
{
alert(a);
}
<div onclick="javascript:test('zaswde');">sdfasdasdadasdasds</div>
Update
<ul>
<li>
<div>
<div onclick="javascript:alert('v'); "></div>
</div>
<div ></div>
</li>
</ul>
Can't i use onclick
on the div element?
I have a div and when a user clicks on it using the onclick
event, i'm calling a function:
function test(a)
{
alert(a);
}
<div onclick="javascript:test('zaswde');">sdfasdasdadasdasds</div>
Update
<ul>
<li>
<div>
<div onclick="javascript:alert('v'); "></div>
</div>
<div ></div>
</li>
</ul>
Can't i use onclick
on the div element?
-
How are you attaching the
onclick
? – loganfsmyth Commented Aug 6, 2012 at 5:43 - 1 How about you show us the whole code? Specifically the div with its onclick code. Is this function above or below that in the HTML? What errors does the console give? – sachleen Commented Aug 6, 2012 at 5:43
- Your code is fine. You have some error somewhere else – zerkms Commented Aug 6, 2012 at 5:49
- @Jalpesh Patel:update my html. – user1415759 Commented Aug 6, 2012 at 5:49
- In its simplest form, the code works. DEMO. You'll have to provide more info/code. – sachleen Commented Aug 6, 2012 at 5:52
3 Answers
Reset to default 2Onclick will call the function, you don't need the javascript:
<div onclick="test('zaswde');">sdfasdasdadasdasds</div>
Your code is working fine.
Moreover You may use click events on any element including <div>
<div onclick="test('This is a <div> tag');">Click on this <div> element</div>
<span onclick="test('This is a <span> tag');">Click on this <span></span>
<p onclick="test('This is a <p> tag');">Click on this <p></p>
<a href="#" onclick="test('This is an <a> tag');">Click on this <a></a>
See An Example Fiddle
Technically, your code will work. But most would argue that it is not the best way to write it.
I guess the reason why it is not working is because you already have a JavaScript error in your HTML page. Check the error console in your browser and see if there are any JavaScript error on it. If yes, then fix that and then this should work.
Edit:
I also see from your example that you don't have anything inside the div. So how are you sure that you are clicking inside the div. See if you can add a senstence or two inside the div, so that you get enough space to click inside the div.