3

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?

Brian David Berman
  • 7,514
  • 26
  • 77
  • 144

2 Answers2

8

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():

event.preventDefault() vs. return false

Community
  • 1
  • 1
karim79
  • 339,989
  • 67
  • 413
  • 406
1

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
  • 81,398
  • 36
  • 149
  • 218