tags:

views:

1028

answers:

1

I might be doing something stupid. But if I have a normal link like:

<div id="changeMe"></div>
<a href="/Not/Intercepted" id="interceptMe">A link</a>

and I attach a jQuery click event to the link like so:

$('#interceptMe').click(function() {
  $('#changeMe').text('Changed');
  return false;
});

Everything works peachy. The page does not get redirected to /Not/Intercepted, which is what I would think would be correct.

Now...

I introduct a ajax call like $.get to my click event and now my page will be incorrectly redirected to the page, which essentially overwrites the ajax call.

$('#interceptMe').click(function() {
  $.get('/Ajax/Call', goesIn, function(comesOut) {
  $('#changeMe').html(comesOut);
    }, "html");
  return false;
});

Is there a way to make jQuery or javascript still intercept the link click so it does not go to the href page? I want to keep the href for those users that aren't enabling javascript. TIA!

+5  A: 

instead of return false, use ....

$("#interceptMe").click(function(event){

    event.preventDefault();

    // Ajax here

    return false; //for good measure
});

http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

I've had many issues with IE especially not listening to return false. Apparently so have others http://coffeeandpaste.blogspot.com/2009/02/javascript-onclick-return-false-does.html

Chad Grant
@rball 'return false' should do the same thing though. I have never had this problem before in 3.5 years of using jQuery. If 'event.preventDefault' works and 'return false' doesn't, please let me know.
KyleFarris
Will do, thanks for the response. I also thought it was odd, but it's happening on everything I have a ajax call on.
rball
@KyleFarris I've had many issues with browsers not working with return false. preventDefault() works so far 100% so I have switched to it for more reliable code. I updated my answer with a link to others having the same issue.
Chad Grant