简体   繁体   中英

Toggle hide not woking

I have a simple code, i want to hide a div if user click on other div.container or button inside this div here is my code

 $('div, button').click(function(){ $('.div').toggle('hide'); }) 
 div{ height: 200px; width: 200px; } .container{ background: pink } .div{ background: blue } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <button>Click</button> </div> <div class="div"></div> 

its work fine when i click on container div but its not working when i click on button, i know the porblem is that you fire a click two times. but how to fix that

You can stop that by preventing the click event from bubbling up the DOM and triggering the click event on the parent with .stopPropagation() :

 $('div, button').click(function(e){ e.stopPropagation(); $('.div').toggle('hide'); }) 
 div{ height: 200px; width: 200px; } .container{ background: pink } .div{ background: blue } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <button>Click</button> </div> <div class="div"></div> 

use below Jquery for the issue.

    $('.container, button').click(function(){
      $('.div').toggle(500);
      return false;
    })

Please try this

$('div, button').click(function(){
  $('.div').toggle('hide');
  console.log("hello");
  return false;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM