PositiveGuy
PositiveGuy

Reputation: 47733

Code is not running on .click of hyperlink

Code is not running on .click when I have this:

$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");                            
});

<a class="cancel" href=""><img src="images/cancelButton.gif" border="0" /></a>

It's got to be something stupid, but I cannot see it.

Upvotes: 2

Views: 278

Answers (5)

Hooray Im Helping
Hooray Im Helping

Reputation: 5264

A couple of people have said add return false; to your click handler. You should instead use the preventDefault method on the event class like so:

$(".cancel").click(function(event) {
  event.preventDefault();
  alert("got here");
  $(this).closest(":dialog").dialog("close");
});

Make sure you pass in the event to the handler function. This is the preferred jQuery way. I also always put the preventDefault() as the first thing in the handler method, but I don't think that makes a difference.

Upvotes: 0

Nicholas Murray
Nicholas Murray

Reputation: 13533

Anywhere you put an onclick event with a javascript call, if you add return false then the default behavior (what would have happened without the onclick event) will be disregarded.

And so in this case return return false will prevent the browser jump to the link anchor.

Edit

Fair comment below - looked at the jquery.com and it says

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

Upvotes: 0

Armstrongest
Armstrongest

Reputation: 15409

I would assume you're wrapping the code in $(document).ready( function () { ... }); ?

$(document).ready( function () {
  $('.cancel').click( function(e) {
     alert('here!');
     e.preventDefault(); // prevents click from following through
  });
});

Upvotes: 7

mkoryak
mkoryak

Reputation: 57918

add return false at the end of your click event:

$(".cancel").click(function() {
    alert("got here");
    $(this).closest(":dialog").dialog("close");
    return false;                            
});

Upvotes: 1

Jeriko
Jeriko

Reputation: 6637

If href="" instead of href="#" doesn't that mean it actually reloads the page on click?

Upvotes: 0

Related Questions