How can I do something on display or visibility change with jquery

1.2k views Asked by At

I want to excecute an action on display or visibility change (really in display:block or visibility:visible) with jquery if posible or javascript, but I've researched a lot in this forum and I couldn't acomodate any of the suggested solutions for similar problems.

The more near that I've been was:

if($('.class').css('display') == 'none'){ // do something }

But obviously this is only an if, and doesn't catch the event and nothing...

Someone could please help me? Thanks

3

There are 3 answers

1
Muhammad Qasim On

give your div element a unique class and check the length of that div, if the length of that div is greater than 0, it means that div exists or vice versa.

if($(".HideDiv").length <1){
<--HideDiv doesnot exist-->

do your code here
}else{
<--HideDiv exists-->

}
<--suppose-->
<div class"HideDiv"></div>

0
Richard Schmidt On

You can use MutationObserver

It would look like this:

var observer = new MutationObserver(function(mutations) {
   if (mutations[0].oldValue.contains('display: none')) {
      alert('The element got visible')
   }
   else if (mutations[0].oldValue.contains('visibility: hidden')) {
      alert('The element got visible')
   }
   else if (mutations[0].oldValue.contains('visibility: visible')) {
      alert('The element got hidden')
   }
   else if (mutations[0].oldValue.contains('display: ')) {
      alert('The element got hidden')
   }
})

observer.observe(document.querySelector('#someselector'), {attributes: true, attributeOldValue: true})

If you need help for your specific case check the docu: Mozilla MutationObserver Documentation

0
Uttam Nath On

<button id="btn" style="display: block;">btn</button>
<p id="demo"></p>

<script>
if(document.getElementById("btn").style.display === "block"){
document.getElementById("demo").innerHTML = document.getElementById("btn").style.display; 
}
</script>

Or

<button id="btn">btn</button>
<p id="demo"></p>

<script>
if(document.getElementById("btn").style.display === "block" || document.getElementById("btn").style.display === ""){
document.getElementById("demo").innerHTML = "notDisplay "+document.getElementById("btn").style.display; 
}
</script>

  • if display not set than js return "" empty string