简体   繁体   中英

Triggering click event of parent div


I have a issue where the .click from the div where my cancel button is nested in triggers when I click the button. This causes both the slideUp and slideDown to trigger at the same time, which results in the div staying visible. I've tried adding a state to prevent the div from sliding down again, but this does not have the desired effect.

$(add).click(function () {
 var inputDiv = Polymer.dom(root_root).querySelector("#inputDiv");
 if(state == 0){
   $(inputDiv).slideDown(300);
  }
 state = 1;
});
 $(cancel).click(function () {
  var inputDiv = Polymer.dom(root_root).querySelector("#inputDiv");
  $(inputDiv).slideUp(300);
  state = 0;
});

https://jsfiddle.net/kkdoneaj/2/

Does anyone know how to work around this issue?

Use Event.stopPropagation() to stop the click from bubbling from the #cancel button to the parent #add div:

$("#cancel").click(function(e) {
    e.stopPropagation();
    ...
});

https://jsfiddle.net/kkdoneaj/3/

you should put stop

Stop the currently-running animation on the matched elements.

$(add).click(function () {
  var inputDiv = Polymer.dom(root_root).querySelector("#inputDiv");
  $(inputDiv).stop().slideDown(300);
});
$("#cancel").click(function (e) {
  var inputDiv = Polymer.dom(root_root).querySelector("#inputDiv");
  $(inputDiv).stop().slideUp(300);
  e.stopPropagation();
});

Others have commented with stopPropagation() , but you can also not expand #inputDiv unless it's already visible, like so:

$(function(){
  $("#add").click(function () {
    if($("#inputDiv").css('display') == 'none'){
      $("#inputDiv").slideDown(1000);
    }
  });
  $("#cancel").click(function () {
    $("#inputDiv").slideUp(1000);
  });
});

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