Home > Enterprise >  jQuery How to add a class to a div if another div has specific class
jQuery How to add a class to a div if another div has specific class

Time:12-03

if any of the webpage elements has is-open class, add open class to another div. doesn't work

is-open is added to div's each time a modal or tab is opened on the page.

<script>
if($(".is-open").length){
$(".blur-screen").addClass("open");
} else {
$(".blur-screen").removeClass("open");    
}        
</script>

CodePudding user response:

The code in your script runs immediately (before is-open is added to a div, because that only happens if a modal or tab is open, which probably doesn't happen immediately when page is loaded).

what you need to do is to call a function that will check it every time a modal/tab is opened

function checkIsOpen() {
  if($(".is-open").length){
    $(".blur-screen").addClass("open");
  } else {
    $(".blur-screen").removeClass("open");    
  }        
}

when modal/tab opens:

checkIsOpen();

CodePudding user response:

Try this,

if($("div").hasClass('is-open')){
  $(".blur-screen").addClass("open");
} else {
  $(".blur-screen").removeClass("open");    
} 
  • Related