Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: click function is not catching the click event on hyperlink

Tags:

jquery

click

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 ?

like image 638
Faizan Ali Avatar asked May 05 '12 22:05

Faizan Ali


People also ask

Why click function is not working in jQuery?

The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.

Why is click not working?

To turn it on, go to Start > Settings > Devices > Mouse > Related Settings > Additional Mouse Options. The Mouse Properties window will pop up. At the bottom of the Buttons tab, you'll see the ClickLock options. Put a tick in the checkbox to enable it.

How do you trigger an event on click?

Trigger Click Event in JavaScript Using click() An element receives the click event when pressed, and a key is released on the pointing device (eg, the left mouse button) while the pointer is within the element. click() is triggered after the down and up mouse events are triggered in that order.

What is $( function () in jQuery?

A function of that nature can be called at any time, anywhere. jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });


1 Answers

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();
  });
});
like image 137
Guffa Avatar answered Sep 27 '22 22:09

Guffa