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>
Related
html
<div id="group1">
<button>buttonA</button>
<button>buttonB</button>
</div>
javascript
$('#group1').on('click', function(event) {
// get ONLY the value of the button cilcked
});
Is something like this possible without attaching an event to every button in the group?
Add a target selector to the on() and use this or event.currentTarget within the handler function to access the matching element the event occurs on
$('#group1').on('click', 'button', function(event) {
console.log($(this).text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="group1">
<button>buttonA</button>
<button>buttonB</button>
</div>
I have a <div class="stock"></div>wrapped around :
<div class="stockAdd"></div>
<div class="stockRemove"></div>
<div class="stockInput"></div>
I want to prevent a click inside my .stock to trigger a function. For now i have the following :
if ($(event.target).is('.stockInput') || $(event.target).is('.stockAdd') || $(event.target).is('.stockRemove')) {
console.log("Ajout stock");
return
}
Isn't there a better way to select thos three divs ? The $(event.target).is('.stock') don't get the job done when i click my nested divs.
Thanks
If I understand you correctly, you want to catch click events on .stockAdd, .stockRemove, and .stockInput, but not on other elements within .stock itself, is that correct?
If so, a delegated event can take care of that without any need to manually check the event target:
$('.stock').on('click', '.stockAdd, .stockRemove, .stockInput', function() {
alert("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAdd">stockAdd</div>
<div class="stockRemove">stockRemove</div>
<div class="stockInput">stockInput</div>
<div>No event</div>
</div>
I would strongly recommend against depending on event.target here; it's too fragile. Any HTML tags nested inside your desired targets would break things:
$('.stock').on('click', function(event) {
if (event.target.className=="stockAll") {
alert("clicked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAll">
This <b> will not work if someone clicks in the bold area</b> but works outside
</div>
</div>
You can add a separate class to all of them like .stock-inner and then grab them all with $('.stock-inner') or you can use a $("div[class^='stock-inner']) - this will grab the parent .stock div...
Also, to reject a click event within the handler you're gunna want to use e.preventDefault() where e is the event object.
the reason it doesn't work well on nested divs is they pass the conditional if in your example, to make it stricter you could add div to selector:
if ($(event.target).is('div.stockInput') || $(event.target).is('div.stockAdd') || $(event.target).is('div.stockRemove'))
You can attach the event on .stock and then filter using the event.target.
HTML
<div class="stock" style="border: 10px solid #000;">
<div class="stockAdd">Add</div>
<div class="stockRemove">Remove</div>
<div class="stockInput">Input</div>
</div>
JavaScript
$('.stock').on('click', function(e) {
if( e.target.className !== 'stock' ) {
console.log(e.target.className);
}
});
jsfiddle
$('.pop').each(function () {
var $elem = $(this);
$elem.popover({
placement: 'auto',
trigger: 'hover',
html: true,
container: $elem,
animation: true,
content: function () {
var pop_dest = $(this).attr("data-pop");
//console.log(plant);
return $("#"+pop_dest).html();
}
});
});
$('#english').click(function() { // ---> THIS PART DOES NOT WORK
alert("english");
});
$('#turkce').click(function() { // ---> THIS PART DOES NOT WORK
console.log("turkce");
});
I have 2 button in popover. But their click event does not work. How can I fire click event from button click ? My html code is below.
<li>
<a href="javascript: void(0);" id="languages" class="pop" data-html="true" data-toggle="popover" data-pop="popper-content" class="popper">
<?=$language["languages"]?>
</a>
<div class="hide" id="popper-content">
<ul class="lang-list">
<li class="en">
<button id="english">English</button>
</li>
<li class="tr">
<button id="turkce">Türkçe</button>
</li>
</ul>
</div>
</li>
When you call the click function, the buttons are not added to to page yet (since they are in a dynamically added popover) so you have to use something that takes care of future added content:
$('body').on('click', '#english', function () {
alert("english");
});
You should delegate the event to make sure the event get's to the desired DOM element if it's not present at the time the js gets executed:
$("body").on('click', '#english', function() {
alert("english");
});
$("body").on('click', '#turkce', function() {
alert("turkce");
});
You can delegate events with jquery by using the on method, where the selector is the parent node that will delegate the event to the children, the firs parameter is the event name click, the second is the child you want the event to be delegated to #english and the third parameter is the handler.
The content of the popover is dynamically appended to the page. This means that when you attempt to attach the event handlers when the page loads neither of the buttons exist in the DOM. To fix the problem use a delegated event handler:
$(document).on('click', '#english', function() {
alert("english");
}).on('click', '#turkce', function() {
console.log("turkce");
});
The problem is that <button> has a default type of submit. You don't want that default behavior since you provided your own click handler. You need buttons of type="button".
<button id="english" type="button">English</button>
I have a div that toggles a modal. I am doing it by either using the built in data-toggle function or the onClick method. Now i want to have a button inside this div that calls a ajax request and does not open the modal.
How could I do this?
Thanks.
Just return false in the button click event listener, here is a simple demo:
$('#ajax').click(function(e){
alert('do ajax');
return false;
})
I was able to do it using the stopPropogation() method:
<div class="col-sm-8 col-md-3" data-target="#modal-1" onclick="toggle_modal(this)">
<div id="1" onclick="toggle_start(this)></div>
</div>
function toggle_modal(clicked_element){
id = $(clicked_element).attr('data-target');
$(id).modal('show');
}
function toggle_start(clicked_element){
alert($(clicked_element).attr('id'));
event.stopPropagation();
}
EDIT--- I realized that the problem here was that the click handler that was bound to the element had to be unbound before I could bind another click handler handler.
I want to allow the user to select/unselect items by click on the element in question. The elements start in an "options" box and if clicked, move to a "selected box". If they are then clicked in the selected box, the elements move back to the original options box.
Can't figure out why delegate() and live() are not working here. I assume this has to do with prependTo() or appendTo().
$('#amen_options .options p').click(function(e){
$(this).appendTo('#amen_selected .options');
e.stopPropagation();
e.preventDefault();
});
/*
$("body").delegate('#amen_selected p', 'click', function(e){
#(this).appendTo('#amen_options .options');
e.stopPropagation();
e.preventDefault();
});
*/
$('div#amen_selected div.options p').live('click',function(e){
$(this).appendTo('#amen_options .options');
e.stopPropagation();
e.preventDefault();
});
Here's the markup:
<div>
<div id="amen_options">
<h3>Click to Select</h3>
<div class="options">
<p data-option="">One</p>
<p data-option="">Two</p>
<p data-option="">Etc...</p>
</div>
</div>
<div id="amen_selected">
<h3>Selected</h3>
<div class="options">
</div>
</div>
The first click works (sending p elements from options to selected box). Once in selected, though, no event handlers are binding. The firebug console isn't showing an error. Normally, I'd assume that this is a markup problem, but I've checked it repeatedly.
Thanks!
It looks like delegate() works good.
http://jsfiddle.net/fLXgU/1/
$('body').delegate('#amen_options .options p', 'click', function(e) {
$(this).appendTo('#amen_selected .options');
return false;
});
$('body').delegate('#amen_selected .options p', 'click', function(e) {
$(this).appendTo('#amen_options .options');
return false;
});