skip to Main Content

<div class="modal fade modal-s" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
                    tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
           content..............
                </div>

by using javascript this div is going display none and block

i want when this div is display block i wiil add a class list to another div and when the none i will remove the class

i have tried this but didnt work the div with id ‘over-lap’ i want to add and remove class from that

document.addEventListener('DOMContentLoaded', function() {
  var mod = document.querySelector('.modal-s');
  var overLapDiv = document.getElementById('over-lap');
  if (mod.style.display == 'none') {
    overLapDiv.classList.remove('overlap-div'); // Fixed typo
  } else if (mod.style.display == 'block'){
    overLapDiv.classList.add('overlap-div');
  }
});

other logic i tried

<body>
  <div class="modal-s show">...</div>
  <div id="over-lap"></div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      var mod = document.querySelector('.modal-s');
      var overLapDiv = document.getElementById('over-lap');
      if (mod.classList.contains('show')) {
        overLapDiv.classList.add('overlap-div');
      } else {
        overLapDiv.classList.remove('overlap-div');
      }
    });
  </script>
</body>

nothing worked

2

Answers


  1. This happens because mod.style.display is empty. You need to use window.getComputedStyle(mod, null).display. Example:

    const mod = document.querySelector('.modal-s');
      
    console.log(mod.style.display); // empty
    console.log(window.getComputedStyle(mod, null).display); // 'block'
    <div class="modal-s show">...</div>
    <div id="over-lap"></div>
    Login or Signup to reply.
  2. //do not use this in if-condition it won't work.
    //mod.style.display == 'none'
    
    
    //make class d-none or any classname so, that it can remove or add
    
    //removing d-none will show div & adding this d-none class will hide the element.
    
    //use classlist.contains
    if(mod.classlist.contains("d-none")){
    }
    
    
    //to remove class from classlist
    mod.classlist.remove("d-none")
    
    //to add class from classlist
    mod.classlist.add("d-none")
    
    
    //there is also toggling (if class is present then it will remove and if not present then add on each event provided)
    mod.classlist.toggle("d-none");
    .d-none{
      display:none;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search