views:

313

answers:

2

I have the following code:

  <script type="text/javascript">

  $(document).ready(function() 
  {
    $("#thang").load("http://www.yahoo.com");

    $(".SmoothLink").click( function()
    {
      $("#thang").fadeOut();

      $("#thang").load($(this).attr("href"));           

      $("#thang").fadeIn();

    });
  });

  </script>

  <a href="http://www.google.com" id="thelink" class="SmoothLink">click here</a><br /><br />
  <div style="border: 1px solid blue;" id="thang">
  </div>

What I am trying to achieve is a quick and easy way to ajax-ify a website by simply putting a class on certain links that I want to load up into a div. The problem I am having is that the normal anchor action is being triggered and just redirecting to the link href normally. How do I suppress the normal anchor action?

+6  A: 

Generally:

$('a').click(function(e) {
    //prevent the 'following' behaviour of hyperlinks by preventing the default action
    e.preventDefault();

    //do stuff

});

or:

$('a').click(function(e) {
    //do stuff

    //equivalent to e.preventDefault AND e.stopPropagation()
    return false;
});

More information:

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

Previous question on the difference between return false and e.preventDefault():

http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false

karim79
Don't you have to pass the e?
Martin
You need to add the `e` parameter to your first function definition, but other than that, light-speed and +1.
Alex Barrett
for the first one, shouldn't there be a var passed into the function called 'e'?
contagious
Yep, you do. Hastily edited.
karim79
And it never hurts to pass the e out of habit anyway.
karim79
+1  A: 

Not exactly related to your problem, but instead of doing this...

$("#thang").fadeOut();
$("#thang").load($(this).attr("href"));
$("#thang").fadeIn();

...jQuery is designed to let you chain methods, as such:

$("#thang").fadeOut().load($(this).attr("href")).fadeIn();
Matt Huggins