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

Short version of the question: see title

Long version of the question: I made extensive use of the jquery show () and hide () functions in my code and just ran into some problem: they work by changing the display attribute of an element to "block" or "none" respectively, so if you have something- what display has: built-in, and then hide and show it, you changed your screen to lock, which will mask the layout in several cases.

In my code, when I want something to be hidden, I give it a "hidden" class. This class is simply {display: none}. I need the changes to show and hide in order to remove or add this class instead of directly changing the display attribute, so that if you add a hidden class and then delete it again (i.e. Hide and show something), go back to exactly how it was supposed to start with (since adding a class overrides attributes rather than directly changing them). Something like this (it's a bit pseucodey, since I don't know how to configure the function correctly - let's say that 'this' is the object that show / hide is called on)

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

how and where can I go from overriding jquery methods? (I'm not a javascript expert)

thanks - max

+4
source share
1 answer

I would not redefine jQuery methods when you could create your own. Overriding can lead to unexpected behavior in plugins.

jQuery already has a method called toggleClass() that seems to match what you are looking for.

 $someElement.toggleClass('hidden'); 

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


EDIT:

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

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

Or create your own method:

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

Before doing this, it would be nice to consult this document:

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

+10
source

Source: https://habr.com/ru/post/1311734/


All Articles