Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 508
Max Williams Avatar asked Dec 22 '22 02:12

Max Williams


1 Answers

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

like image 103
user113716 Avatar answered Jan 04 '23 22:01

user113716