Home > Software design >  addEventListener inside if statement wont work for toggle click event
addEventListener inside if statement wont work for toggle click event

Time:06-17

kindly asking a question, my goal is
click div
show or hide div
or click outside div to hide div

after adding addEventListner inside if statement , it just run a single click then doesn't toggle anymore How to fix that, Thank you!

$(document).ready(function() {
  $(document).on('click', '.head', function(elem) { // click div with class = head
    var toggle = elem.target.getElementsByClassName('toggle')[0]
    if (toggle.style.display = "none") {
      toggle.style.display = "";

      document.addEventListener('click', function() {
        toggle.style.display = "none";
      })
    } else {
      toggle.style.display = "none";
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div >expand
    <div  style="display:none;">
      <p>number 1</p>
      <p>number 2</p>
    </div>
  </div>
</div>

CodePudding user response:

Try this ;)

$(document).ready(function() {
  var toggle = document.getElementsByClassName("toggle")[0];
  
  document.addEventListener('click', function() {
    if (toggle.style.display !== "none") {
      toggle.style.display = "none";
    }
  });

  $(document).on('click', '.head', function(elem) { // click div with class = head      
    if (toggle.style.display = "none") {
      toggle.style.display = "";
    } else {
      toggle.style.display = "none";
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div >expand
    <div  style="display:none;">
      <p>number 1</p>
      <p>number 2</p>
    </div>
  </div>
</div>

CodePudding user response:

I managed to fix the script by using once:true; or one() that recommended by @freedomn-m
Thank you guys for all the comments and answers

pure js

$(document).ready(function() {
  $(document).on('click', '.head', function(elem) { // click div with class = head
    var toggle = elem.target.getElementsByClassName('toggle')[0]
    if (toggle.style.display == "none") {
      toggle.style.display = "";
      
        document.addEventListener('click',function(){
            toggle.style.display = "none";
        }, {
        once: true,
        });
    } else {
      toggle.style.display = "none";
    }
  })
})

jquery

$(document).ready(function() {
  $(document).on('click', '.head', function(elem) { // click div with class = head
    var toggle = elem.target.getElementsByClassName('toggle')[0]
    if (toggle.style.display == "none") {
      toggle.style.display = "";
      
        $(document).one('click',function(){
          toggle.style.display = "none";  
        })
        
    } else {
      toggle.style.display = "none";
    }
  })
})
  • Related