Max Williams
Max Williams

Reputation: 32933

How to override jquery's show() and hide() functions

Short version of question: see title

Long version of question: I've used jquery's show() and hide() functions extensively in my code and just encountered a bit of a problem: they work by changing the display attribute of the element to 'block' or 'none' respectively, so that if you have somethin that has display: inline and then hide and show it, you've changed its display to block, which screws up the layout in a couple of cases.

In my code, whenever i want something to be hidden initially i give it a class 'hidden'. This class is simply {display: none}. I'd like the change show and hide to remove or add this class, instead of directly changing the display attribute, so that if you add the hidden class and then remove it again (ie hide and show something) then it's back to exactly how it was to start off with (since adding a class overrides the attributes rather than directly changing them). Something like this (this is a little pseucodey as i don't know how to set the function up properly - let's assume that 'this' is the object that show/hide was called on)

function show(){
  this.removeClass("hidden");
} 

function hide(){
  this.addClass("hidden");
} 

how and where would i go about overriding the jquery methods? (I'm not a javascript expert)

thanks - max

Upvotes: 4

Views: 6665

Answers (1)

user113716
user113716

Reputation: 322462

I wouldn't override jQuery's methods when you could create your own. Overriding would very likely cause unexpected behavior in plugins.

jQuery already has a method called toggleClass() that would seem to fit what you're looking for.

$someElement.toggleClass('hidden');

Docs: http://api.jquery.com/toggleClass/


EDIT:

But to answer your specific question, to override a jQuery method, you would do something like this:

jQuery.fn.show = function() {
    // Your custom code
}

Or to create a custom method:

jQuery.fn.customMethod = function() {
    // Your custom code
}

Before doing so, it would be a good idea to consult this document:

http://docs.jquery.com/Plugins/Authoring

Upvotes: 11

Related Questions