0

I have a div that is shown / hidden through CSS media queries.

I want to trigger a JQuery call when this div becomes visible - triggering once if the div changes from

display: none;

to

display: block;

Is this possible to do?

Something like the onclick call, but on the div property changing to visible?

$(document).on('click', '#mydiv', function() {
}
R2D2
  • 2,620
  • 4
  • 24
  • 46

3 Answers3

1

UPDATED to handle it on page load

Use window.matchMedia() with rule used for the div to become visible and set relevant event listener filtering by event matches property.

Here an example BUT you have to use your own media queries rule.

var widthMatch = window.matchMedia("(min-width:500px)");
if(widthMatch.matches) {
  divIsVisible();
}
widthMatch.addListener(function(e){
  if(e.matches) {    
    divIsVisible();
  }
});

function divIsVisible(){
  console.log('DIV is visible!')
}

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I never knew something like this existed. Learned something new. +1. Just a question, is this approach also expensive like DOM mutator? – Rajesh Dec 09 '17 at 16:54
  • Regarding OP expected behaviour, this is for sure better and i've never heard about any performance issue regarding native `window.matchMedia()` API (there is some regarding polyfill for older browsers though) – A. Wolff Dec 09 '17 at 17:58
0

$(document).ready(function(){
function myFunction(){
setTimeout(function(){ console.log('foo foo') }, 2000)
}
$(document).click(function(){
$('#demo').css('display','block');
//after div is visible myFunction is triggered
myFunction();
})

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>click</h1>
<div id='demo' style='display:none'>
<p>hello world</p>
</div>
vicky patel
  • 699
  • 2
  • 8
  • 14
0

You could use $(window).resize() to detect these css display changes on the desired element:

$(window).resize(function() {
  var divDisplay = $('.mobileHide').css("display");
  if (divDisplay === "block") {
    $('.status').css('display', 'block');
    //do stuff
  } else {
    $('.status').css('display', 'none');
  }
});

See resizable fiddle

Syden
  • 8,425
  • 5
  • 26
  • 45