I have a little web app in which I show and hide DIVs a lot. Sometimes, however, I need to add a CSS class to that div that hides the div (using display:none rather than jQuery’s hide() function) because I still need to know if the given div was initial shown on the screen. I typically use jQuery’s addClass and removeClass accordingly.
However, I am running into a problem when doing this. It seems like if the div has been hidden and shown before, adding a display:none class to the div will not work.
I was wondering if there was any kind of work around that I could use without resorting to using hide().
Here are some JSFiddle examples to show you what I am talking about:
JSFiddle Example 1 – Will properly Hide the DIV using the CSS class.
JSFiddle Example 2 – After using the show() and hide() functions, it will not properly hide the DIV using the CSS class.
The problem you encounter is that jQuery’s hide()-function adds inline CSS to the element:
Where display is set to
block, so your hideDiv class will get overwritten by the inline since it’s considered “stricter” in CSS rules. A somewhat ugly workaround to this is to change your hideDiv CSS rule to this:The
!importantpart will make it take precedence over the inline CSS.Edit:
Additionally, I would recommend sticking with one way to show/hide stuff (your own or jQuery). Use jQuery show/hide for all showing/hiding but you can still add a class for tracking, just don’t have that class hide your elements.
So chance the button JavaScript to something like this:
And completely remove the hiding CSS from the hideDiv class. Now you can still use jQuery to find the div(s) hidden after page-load without running into hiding/showing not working and without having to resort to
!important.A more elegant solution to your issue, I’d say.