Why does the condition in the function not work? Please tell me why the .not() condition does not work.
$(".one").not(".two").on("click", function() {
console.log("click one");
})
.one {
width: 500px;
height: 300px;
background: grey;
position: relative;
}
.two {
background: red;
position: absolute;
top: 20px;
right: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input type="file" >
</div>
CodePudding user response:
That's because of event bubbling.
When you click on .two
, as it is a child of .one
, the click event happens also on .one
To prevent this, you can use event.stopPropagation()
but it might not be the right choice as it - indeed - stops the event propagation to every other element, and this could not be desirable if there are other events you listen to in your code and introduce bugs. Stopping propagation of events is something that should be used carefully:
Another - and in my opinion preferred - option is to use the event.currentTarget
and event.target
. The first is the element to which the event is attached (.one
in your case). The second is the actual HTML element that has been clicked.
So, you can check if the event.target is two
or one
and code different behavior for each alternative.
$(".one").on("click", function(event) {
console.log("event.target is: ", event.target);
console.log("event.currentTarget is: ", event.currentTarget);
if ($(event.target).hasClass('two')) {
console.log("Mmh... you clicked two, please click one");
} else if ($(event.target).hasClass('one')) {
console.log("YEAH! You clicked one this time");
}
})
.one {
width: 500px;
height: 300px;
background: grey;
position: relative;
}
.two {
background: red;
position: absolute;
top: 20px;
right: 0px;
}
.as-console-wrapper { max-height: 4.5em !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input type="file" >
</div>
CodePudding user response:
$(".two").on("click", function(e) {
e.stopPropagation();
})