I have in my project a window click eventListener and some click events on div elements. If i click on the div the click event on this div-element (correct) and the window click eventListener fires (not correct).
Can I bubble the div element that the window click eventListener do not fire the event?
For a better demonstration jsfiddle:
window.addEventListener('mouseup', onDocumentMouseUp, false);
function onDocumentMouseUp(event){
alert('dont fire this event on button click')
}
$('#button').on({
click: function (event) {
alert('button click event');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" style="height: 30px; width: 30px; background: blue"></div>
I hope somebody can help me.
Yes, you can use event.stopPropagation() like this:
$('#button').on({
click: function (event) {
alert('button click event');
event.stopPropagation();
}
});
Related
I have a button over another button in a way like this
<button id="button1" style="width:200px; height:200px; position:relative; border: 1px solid;">
test
</button>
<script>
document.getElementById("button1").onclick = function(e) {
console.log("button1 click");
}
document.getElementById("button2").onclick = function(e) {
console.log("button2 click");
}
</script>
When I click on button2, also the button1 is clicked, but I would only capture button2 click
Tried with e.preventDefault() without success...
First of all, I think it's not valid HTML. You shouldn't have a <a> tag inside <button>
For more information about <button> check this.
You're facing this problem because of event bubbling. Check this links for more details regarding event bubbling.
https://javascript.info/bubbling-and-capturing
You can fix this problem using event.stopPropagation(); But I must say it's not the right approach
This happens because of bubbling. Event runs the handlers on every parent all the way up. You could do something like this to fix this.
<button id="button1" style="width:200px; height:200px; position:relative; border: 1px solid;">
test
</button>
<script>
document.getElementById("button1").onclick = function(e) {
console.log("button1 click");
}
document.getElementById("button2").onclick = function(e) {
console.log("button2 click");
e.stopPropagation();
}
</script>
Here's the situation. There is button and there is hidden div. After user clicks the button, hidden div appears and in the same time I'm adding event listener on body using on() to check if user clicked out of this hidden div. After that div should be hidden again and click event detached.
Everything works fine but only when user clicks the button. If I trigger click using trigger() function then on() function is called immediately and hidden div is not appearing.
Here is the code:
$('button').click(function(e){
e.stopPropagation();
$('div').toggleClass('active');
if($('div').hasClass('active')){
$('body').on('click.div', function(e){
console.log('body clicked')
if(! $(e.target).closest('div').length){
$('div').removeClass('active');
$('body').off('.div');
}
});
}else{
$('body').off('.div');
}
});
$('input').click(function(){
$('button').trigger('click');
});
div{
display: none;
}
div.active{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
I found also solution how to solve this problem, but I still dont know why using trigger() and stopPropagation() does not work.
Here is fixed code with using setTimeout():
$('button').click(function(e) {
e.stopPropagation();
$('div').toggleClass('active');
if ($('div').hasClass('active')) {
setTimeout(function() {
$('body').on('click.div', function(e) {
console.log('body clicked')
if (!$(e.target).closest('div').length) {
$('div').removeClass('active');
$('body').off('.div');
}
});
}, 0);
} else {
$('body').off('.div');
}
});
$('input').click(function() {
$('button').trigger('click');
});
div {
display: none;
}
div.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
The reason is that the click on the input that you responded to by calling trigger propagates to body, and so it gets handled by the body handler you add. That is, the click that triggers this event handler:
$('input').click(function(){
$('button').trigger('click');
});
...gets processed; and then of course you're sending another one later.
To fix it, just stop that click from propagating:
$('input').click(function(e){
e.stopPropagation();
$('button').trigger('click');
});
$('button').click(function(e){
e.stopPropagation();
$('div').toggleClass('active');
if($('div').hasClass('active')){
$('body').on('click.div', function(e){
console.log('body clicked')
if(! $(e.target).closest('div').length){
$('div').removeClass('active');
$('body').off('.div');
}
});
}else{
$('body').off('.div');
}
});
$('input').click(function(e){
e.stopPropagation();
$('button').trigger('click');
});
div{
display: none;
}
div.active{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
The reason your setTimeout version worked is that you were delaying hooking up your body click handler until after the click on the input had reached body, so it didn't get triggered by the click on the input.
This question already has answers here:
How to stop events bubbling in jQuery? [duplicate]
(5 answers)
Closed 7 years ago.
I am trying to call a jQuery function when clicked only on parent element.
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework()" src="img/clicker.png" />
</div>
I have an img tag inside a div. When I click on the div it should call one function and when I click on the img I want to call another function. How can I do this?
$('.click-img, .wishes').click(function () {
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
When I click the div I should call the above function. However now when I click on the image, it is also calling this function and createFirework().
The issue is due to event bubbling. If you attach your events in an unobtrusive manner you can easily stop this behaviour.
<div id="clcbox" class="click-img">
<img id="fire" src="img/clicker.png" />
</div>
$('#fire').click(function(e) {
e.stopPropagation();
createFirework();
});
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.preventDefault();
});
First off, don't mix inline (onclick) event handlers and jQuery event handlers. Once, you've got a jQuery event handler in place of your createFirework method, you simply stopPropagation to stop it calling the handler on the outer div.
Below is an example
$('.outer').click(function(e){
alert("You clicked text in the div");
});
$('.inner').click(function(e){
alert("You clicked the button, but the div event handler will not fire");
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<span>here is some text inside the div, click it</span>
<button class="inner">Click me</button>
</div>
You need to use stopPropagation function:
http://www.w3schools.com/jquery/event_stoppropagation.asp
In your case you need to add this on image click event:
$('.click-img, .wishes').click(function (event) {
event.stopPropagation();
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
It looks like you need to stop the click event from the image bubbling up the DOM chain.
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.stopPropagation();
});
When you click on the image, that event is passed up to it's parent, in this case the <div>. That is by behavior. To stop that from ocurring, you call the stopPropagation() function that is part of the incoming event argument for the click event.
You can use Event.stopPropagation(), to stop the click event bubble to its parents, but you also need to add a param event, so your function can access it without browser issue.
// VVVV pass `event` as createFirework's param.
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
But I'd suggest that answers that separate js part and html part would be better. Just like Jamiec's.
function createFirework(event) {
console.log('inner');
event.stopPropagation();
}
$('.click-img, .wishes').click(function () {
console.log('outer');
return false;
});
#clcbox {
width: 100px;
height: 100px;
border: solid 1px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
</div>
I have two buttons (on and off). When I click "on," I want to turn on the function called turnToolOn, and when I click "off," I want to turn off the function. I have this now:
$("body").on("click", "#turnOn", turnToolOn);
$("body").off("click", "#turnOff", turnToolOn);
The on() function is working, but I can't seem to get my function to stop executing when I click "off."
You need to wrap your on/off events in a "click" event, and use the ID of the actual element you're using as the button to activate it.
So, if you have a button <button id="turnOn">On</button> and <button id="turnOff">Off</button>:
$( "#turnOn" ).click(function() {
$( "body" )
.on( "click", turnToolOn )
});
$( "#turnOff" ).click(function() {
$( "body" )
.off( "click", turnToolOn )
});
Read more at the jQuery API Docs site for the off() event handler!
As said in the comments, the calls you have only enable/disable certain event listeners in the DOM. If you need functions that start/stop something, you need to define them. Assuming that turnToolOn does what you expect it to do, you need to write its "counter" function (say turnToolOff) and use that as a handler attached to your off button:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff); /// <--- here it is
And if you don't plan to remove/add on/off buttons dynamically (you can't have more than one anyway since you're using IDs), you can drop the delegated event handler (on()) and use regular binding after the DOM is ready.
Here is a super simple example that uses this to toggle a class of an element:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff);
function turnToolOn() {
$('#el').addClass('on');
}
function turnToolOff() {
$('#el').removeClass('on');
}
#el {
width: 50px;
height: 50px;
background: #eee;
}
#el.on {
background: #0c0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="turnOn">On</button><button id="turnOff">Off</button>
<br />
<div id="el"></div>
And here is what on/off functions can do (binding/unbinding event handlers), so you can understand it better:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff);
function turnToolOn() {
$("body").on("click", "#trigger", triggerCall);
alert('trigger handler attached');
}
function turnToolOff() {
$("body").off("click", "#trigger", triggerCall);
alert('trigger handler detached');
}
function triggerCall() {
$('#el').toggleClass('on');
}
#el {
width: 50px;
height: 50px;
background: #eee;
}
#el.on {
background: #0c0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="turnOn">On</button><button id="turnOff">Off</button>
<button id="trigger">Trigger</button>
<br />
<div id="el"></div>
I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});