0

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

  • Does this answer your questoin [Is it possible to listen to a "style change" event?](https://stackoverflow.com/questions/2157963/is-it-possible-to-listen-to-a-style-change-event) – kiranvj Jun 08 '22 at 12:57
  • I would first ask. "For what do you need that"? I develop software for over 40 years now and never had that requirement. Normally your software is doing the DOM changes. Who else is allowed to change your DOM without your knowledge? – Thallius Jun 09 '22 at 06:57

3 Answers3

0

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>
  • Yes but this snippet dooesn't listen no? I'm looking for a script which listen for display or visibility changes to run... – trying2code Jun 08 '22 at 16:50
0

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

<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
Uttam Nath
  • 644
  • 4
  • 16