Reputation: 1564
I have a jquery which needs to fire when on click event. When I try it on site like w3schoools try jquery, it fires. But in my application, it fails to fire. Below is my script.
<script>
$(document).ready(function(){
$(".vouch").click(function(){
alert("000");
});
});
</script>
</head>
<body>
<li class="vouch">
<a href=""><span>tooo</span></a>
</li>
When i change the class .vouch
to a different class, it fires. seems like there is something blocking the working of the code. Any assistance is greatly appreciated.
Upvotes: 0
Views: 66
Reputation: 92983
In your code, the click
event is being attached to the .vouch
element at the time of document.ready
, but then is "stuck" to that element. Even if you change the class, the event handler remains bound to the li
element itself.
To do what you want, use event delegation. This delegates the click
event to the document
instead, but checks if the clicked element has the vouch
class at the time of the click before executing the code.
$(document).ready(function () {
$(document).on('click', '.vouch', function () {
alert("000");
});
});
http://jsfiddle.net/mblase75/H88PU/
Upvotes: 1
Reputation: 12367
You have to include jQuery in your head
: it's an external library.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Whenever something doesn't work in JS, it's a good idea to check your browser console for errors.
In this case, you would have seen something like $ is not defined
, which usually means that you didn't include jQuery or you're trying to execute your JS before jQuery loads.
Upvotes: 0
Reputation: 5361
Add this in your <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
and it should work
Upvotes: 0