jQuery Documentation: Events Guide

Josh Langner said on November 06, 2008

Michael Thompson, I've noticed that "return false;" also prevents showing a # sign / jumping to a URL as a browser would expect. So for example:

$('.tab').click(function() {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    return false;
});

Would this not also be correct?

Josh Langner said on November 06, 2008

@Michael Thompson eh... nevermind. Reread your post for the 5th and I finally got what you were saying. :)

Thomas Eilander | Santhos said on November 07, 2008

Seems like a very smart and easy to use solution! Thanks for sharing!

olivier said on November 07, 2008

why "p" ?

Jonathan Snook said on November 07, 2008

p = parent. Admittedly, I tend to be concise in my variable naming. I probably shouldn't be when it comes to sharing code. :)

Rasmus said on November 07, 2008

Why not cache the last active element? Or is that too obvious?

I'm no jQuery-guy so I'll just post the lines you'd need. Not sure you'd need the parent at all then. I hope it makes sense ;)


      var active; // define variable to contain last active element in a parent scope
...
            if (active) active.removeClass('active'); // remove class from last active element
            active = $(this).addClass('active');
S??rgio Jardim said on November 09, 2008

I'd like to pass the class name also. So I can use any name, instead of .active.

(function($){
$.fn.switcheroo = function(els, activedClass){
if(!activedClass) {
activedClass= ".active"; //it's now a suggestion, not a fixed one
} else { //concatenate a dot
activedClass= "."+activedClass;
};
this.each(function(){
var p = $(this);
$(els||'li', p).click(function(e){
$(activedClass, p).removeClass(activedClass);
$(this).addClass(activedClass);
e.preventDefault();
});
});
}
}(jQuery));

Abba Bryant said on November 14, 2008

Is it actually necessary to concatenate the "." into the className above?
I thought the addClass function would take care of that.

test said on November 23, 2008

TEST1

Jack F said on December 08, 2008

Hey Jonathan,

I'm looking to really go further with JQuery and wondering how you learnt so much - was there a specific resource you used, such as a website/book etc?

Thanks!

Jack F

Jonathan Snook said on December 08, 2008

@Jack F: I'm self-taught so no specific site except the jQuery docs and learning from what other people put out. Half the battle is understanding the methodology of the library (for jQuery, knowing that most(/all?) calls return the jQuery object, how plugins work, learning the API, etc).

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.
f2富二代官网入口