0

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.

3
  • 3
    include jquery reference in your code it will work for sure Commented Jun 3, 2014 at 13:53
  • 1
    Any error messages in the browser console? Commented Jun 3, 2014 at 13:56
  • 1
    You have some invalid markup there. li should be nested within ul or ol. Commented Jun 3, 2014 at 13:58

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Now i understand what "stuck" means.. the classes are dynamically changed by other javascript. so this could be a problem which i never thought of. Thanks.
0

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

Comments

0

You have to include jQuery in your head: it's an external library.

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

Your code works fine.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.