Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .click() event troubles

Here's a snippet of my code:

    $(".item").click(function () {
        alert("clicked!");
    });

And I have (hypothetically; in actuality it's far more complicated) the following on my page:

<a href="#" class="item"><img src="1.jpg" /></a>

However, when I click the image, I do not get an alert.

What is my mistake?

like image 420
Isaac Avatar asked Feb 22 '26 11:02

Isaac


2 Answers

Is your selector actually matching anything? Try using the jQuery debug plugin (http://jquery.glyphix.com/) and doing this:

$(".item").debug().click(function() {
    alert("clicked!");
});

.debug() will log whatever is matched to the Firebug console (you are using firebug, right? :-) ) without "breaking the chain" so you can use it inline like this.

If that turns out correctly, there may be some issue with the browser navigating to "#" before it can show your alert. Try using the .preventDefault() method on the event object to prevent this behavior:

$(".item").click(function(evt) {
    evt.preventDefault();
    alert("clicked!");
});
like image 50
Matt Avatar answered Feb 24 '26 23:02

Matt


First question - are you adding the element to be clicked dynamically? If it is, you should use the live event since that will take care dynamically created elements.

http://docs.jquery.com/Events/live#typefn

like image 25
DLS Avatar answered Feb 25 '26 00:02

DLS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!