@Michael Thompson eh... nevermind. Reread your post for the 5th and I finally got what you were saying. :)
Seems like a very smart and easy to use solution! Thanks for sharing!
why "p" ?
p = parent. Admittedly, I tend to be concise in my variable naming. I probably shouldn't be when it comes to sharing code. :)
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');
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));
Is it actually necessary to concatenate the "." into the className above?
I thought the addClass function would take care of that.
TEST1
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
@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).
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:
Would this not also be correct?