Jquery "hasClass ()" not working?

I need to hide a div if another div has a class.

I created a very simple example HERE

I need a div below to hide when the word "click" is .. well .. snapped. It adds the class to the middle div just fine, but it seems that hasClass() doesn't want to work?

NOTE: The structure should be like this. If you click β€œclick”, change the middle div (add a class?) And manipulate the lower div based on the middle div. With this setting - I can't just do "if CLICK is clicked, slideUp () is the bottom div".

Also, after clicking "ok" or "cancel", it will return because the middle div will no longer have a class. Provided that the method I can get here is haha.

+4
source share
6 answers

your if is outside of any function, so there is no reason to call it after loading the script.

Check out this script , I think you want it.

+3
source

On a side note, another variation to check if there is a class:

 if ( $('body.className').length ) { 

I still recommend hasClass. It's just nice to see changes sometimes.

+3
source

As others have already mentioned, you do not have an if call for all click event handlers. Create a custom function with an instruction inside the if and call it for all click handlers.

Tick fiddle

+2
source

After adding the class to the DOM element, this should correctly hide the element.

 $('.element').click(function() { $('.thisElement').addClass('hidepub'); if($('.thisElement').hasClass('hidepub')) { $('.thisElement').hide(); } }); 
+1
source

This is called only once when the script loads. You need to make sure that it is called in your .click(...) handler.

 if($('#timestampdiv').hasClass('hidepub')) { $('#major-publishing-actions').slideUp('slow'); } 
+1
source

You can combine them all into one function - And you want this check to be inside the click functions

You can reduce the extra addclass layer by using toggleClass and going into state

 $('a.edit-timestamp,a.save-timestamp,a.cancel-timestamp').click(function() { var $tsdiv = $("#timestampdiv"); // add class showpub if edit is clicked $tsdiv.toggleClass('showpub',$(this).hasClass('edit-timestamp')); // add class hidepub only if it wasn't edit that was clicked $tsdiv.toggleClass('hidepub',!$(this).hasClass('edit-timestamp')); // then do your toggle if ($tsdiv.hasClass('hidepub')) { $('#major-publishing-actions').slideUp('slow'); }else{ $('#major-publishing-actions').slideDown('slow'); } }); 

http://jsfiddle.net/JPcge/

You can undo it by replacing the logic passed to toggleClass () methods

0
source

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


All Articles