5

I have the following piece of code

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        $('body').on('click', 'a.wishlist_item', function(){
            alert('asas');
            return false;
        })
    </script>
</head>
<body>
<a class="wishlist_item" id="wishlist_item" href="#" >Add to wishlist</a>
</body>
</html>

The code is supposed to alert when I click on the hyperlink with wishlist_item class. but its not working.. is there anything that I may be doing wrong in this code ?

1 Answer 1

8

You have to bind the event after the element exists. Use the ready event to run the code when all the page is loaded:

$(document).ready(function(){
  $('body').on('click', 'a.wishlist_item', function(e){
    alert('asas');
    e.preventDefault();
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot man.. its working fine now.. saved me a lot of time !!

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.