tags:

views:

33

answers:

3

Hello everyone,

I would like to know if there is a way to disable the current class from reloading the page with jQuery?

For example, when you are on the About page the current state for the About page doesn't allow the users to reload the page if they click on the link again. So, if you have some kind of animation it won't start over.

If someone can lend me a hand I will greatly appreciate it.

Thank you,

This is what I have so far:

$(function() {
    $page = jQuery.url.attr("file");
    if (!$page) {
        $page = 'index.html';
    }
    $('ul.navigation li a').each(function() {
        var $href = $(this).attr('href');
        if (($href == $page) || ($href == '')) {
            $(this).addClass('current');
        } else {
            $(this).removeClass('current');
        }
    });
});
A: 

You have to catch the click event and cancel it. See the part I added between my comments below:

$(function(){
 $page = jQuery.url.attr("file");
 if(!$page) {
  $page = 'index.html';
 }
 $('ul.navigation li a').each(function(){
  var $href = $(this).attr('href');
  if ( ($href == $page) || ($href == '') ) {
   $(this).addClass('current');

   /** ADDED BELOW **/
   $(this).click(function(event) {
     event.preventDefault();
     event.stopPropagation();
   });
   /** ADDED ABOVE **/

  } else {
   $(this).removeClass('current');
  }
 });
});
Ben Lee
Note that "event.preventDefault()" stops the click from reloading the page, and "event.stopPropagation()" stops the event from bubbling up to other event handlers.
Ben Lee
Also, as general good practice, you probably shouldn't name your variables starting with a dollars sign unless you have a good reason to (for example, if the named variable is a jquery-extending object). Your plain strings above named "$page" and "$href" would probably be better to be called simply "page" and "href".
Ben Lee
@Ben Lee, Thanks again for your help and the next Time I have a question I will make sure I put my code into code blocks and name my variables.
Kmack
A: 

You could disable the link by replacing $(this).addClass('current') with:

$(this).addClass('current').find("a").click( function() {
  return false;                     
})

This has worked for me in the past but have just seen Ben's update and am interested if mine and his answers will both work or whether mine is flawed? Is event.preventDefault(); and event.stopPropagation() the better option?

Steve Claridge
As a matter of style, people tend to prefer preventDefault over returning false. Returning false works, for archaic reasons, but it is really sort of a hack. See this SO post for a discussion: http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false
Ben Lee
A: 

How about dynamically adding a hash to the link of the current page? Clicking a link with a hash in the url won't reload the page. (The a DOM element has a property named "hash" that can be used for this.)

Anders Fjeldstad