Stop JS-event propagation on table row click - javascript

I have the following HTML-table:
<table>
<tr>
<td>
Row 1
</td>
<td>
<!-- Hidden JSF-button -->
<button class="hide" />
</td>
</tr>
</table>
When I click on a tr, I trigger a click on the hidden button with JS:
$('table tr').on('click', function(e) {
var $button = $(this).find('button');
console.log('trigger click on', $button);
$button.trigger('click');
});
The click event propagates up, and will cause a never ending loop (can be seen here: http://codepen.io/anon/pen/kDxHy)
After some searching on Stack Overflow, it is clear that the solution is to call event.stopPropagation,
like this (can be seen here: http://codepen.io/anon/pen/BnlfA):
$('table tr').on('click', function(e) {
var $button = $(this).find('button');
// Prevent the event from bubbling up the DOM tree.
$button
.off('click')
.on('click', function(e) {
console.log('click');
e.stopPropagation();
return true;
});
console.log('trigger click on', $button);
$button.trigger('click');
});
The solution above works. But it feels like a hack, and I don't like it.
Do I have to register a click handler on the on the $button just to call event.stopPropagation? Are there any better way(s) of preventing the click event from bubbling?

A better overall solution would be not to trigger the click event at all but simply have a seperate function that you can call and that encapsulates the event handler logic.
function doSomething(someArg) {
//do something
}
$('button').click(function () {
doSomething(/*pass whatever you want*/);
});
$('table tr').on('click', function () {
doSomething(/*pass whatever you want*/);
});
Please note that doSomething doesn't have an event handler signature such as (e). That's generally a good practice to pass just what's needed to the function to do it's own work, not the whole event object. That will simplify the implementation of doSomething and decouple it completely from the event object.
EDIT:
Sorry, but I need to manually trigger the button click when the user
clicks on a tr. Please see my comment to #magyar1984 question.
In this case you probably found the best solution already, which is to attach an event listener on the button and call stopPropagation. You could also look into getting all click event handlers by using the events data on the element, but beware that you would then be relying on jQuery internals so the code could break in future releases.
Have a look at this question to know how to retrieve the event handlers.

I was able to get it to only register the button click once by updating your codepen to the following:
var handleClick = function(e) {
var $button = $(this).find('button');
console.log('trigger click on', $button);
$button.trigger('click');
};
$('button.hide').on('click',function(e){
e.stopPropagation();
});
$(function() {
$('table tr')
.on('click', handleClick);
});
But the general idea is to declare an onClick event on the button and stop the propagation there.

Modifying buttons behaviour, expecially in frameworks, can cause some unexpected issues. You could add a flag to the row and use it to check if the button should be clicked. But you have to know how many click are automatically generated and should be omitted.
var handleClick = function(e) {
var $button = $(this).find('button');
console.log('triggerring click on...', $button);
if (this.clicked !== true) {
console.log('and clicked!')
this.clicked = true;
$button.trigger('click');
} else
this.clicked = false;
};
Here's the code: http://codepen.io/anon/pen/dJroL

Related

Checking button click event and doing something and removing them if user clicks elsewhere

I am attaching a onclick function to the button#1 and according to this function i am changing other buttons' opacity and disabling user to click on them.
But I want to undo what has been changed onclick event, making other buttons as normal.
My javascript and jquery code as below;
btnLink.onclick = function(e) {
var divToShow = document.getElementById('linkNewDiv');
console.log('clicked');
divToShow.style.display = 'inherit';
$(btnVideo).prop('disabled',true);
$(btnVideo).addClass('opacityReducing');
$(btnPicture).addClass('opacityReducing');
$(btnPublish).addClass('opacityReducing');
$(btnPicture).prop('disabled',true);
$(btnPublish).prop('disabled',true);
$(btnCheck).addClass('opacityReducing');
}
I couldnt manage to figure it. I found a one way if user clicks outside of the elements I am changing elements style and disable property by writing all these codes again. Any better solutions ? Thanks :)
You can achieve this with stopPropagation(). I made some changes to your code to make it more readable, check this:
$(document).on('click', function(e) {
console.log('clicked');
$('#linkNewDiv').css("display", "inherit");
$(btnVideo, btnPicture, btnPublish).removeClass('opacityReducing').prop('disabled', false);
$(btnCheck).removeClass('opacityReducing');
});
$('#bnLink').on('click', function(e) {
e.stopPropagation();
console.log('clicked');
$('#linkNewDiv').css("display", "inherit");
$(btnVideo, btnPicture, btnPublish).addClass('opacityReducing').prop('disabled', true);
$(btnCheck).addClass('opacityReducing');
});

Prevent click on outer li while clicking on inner link

I have some lis including a links as below
<li>
<span>SomeText</span>
<a href='someurl' class='entityDetailModal'>sometext</a>
</li>
I am using a third party library ('LightGallery') that adds click event on Li, and by Jquery I have add click event to the links to show a dialog.
The problem is when I click on link both click event will be fired,
my click event handler is
$('body').on("click", 'a.entityDetailModal', function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
I tried event.stopPropagation() and event.preventDefault(); and return false; in link onclick event handler but they don't work.
Sample:http://jsfiddle.net/HuKab/30/
How can I overcome this?
Update
It seems the problem is the way I add click event handler,
using this way it seems that everything is ok
$('a.entityDetailModal').click(function (event) {
event.preventDefault();
event.stopPropagation();
loadDialog(this, event, '#mainContainer', true, true, false);
return false;
});
Update 2
Thanks #Huangism, this post stackoverflow.com/questions/16492254/pros-and-cons-of-using-e-stoppropagation-to-prevent-event-bubbling is explaining the reason.
Use stopPropagation(); in child element
$("li").click(function (e) {
alert("li");
});
$("a").click(function (e) {
e.preventDefault(); // stop the default action if u need
e.stopPropagation();
alert("a");
});
DEMO
It is not very clear to me what your problem really is. If you simply want to get rid of the click on the li tag you may use .unbind() from jQuery (see: http://api.jquery.com/unbind/). You should end up with only your click event.
Another thing that might help is to use something like:
$("a").on('click.myContext', function(event) {
//Your action goes here
}
This way you can have parallel events and turn them on with $("a").on('click.myContext') and off with $("a").off('click.myContext')
Edit: Use:
$("a").on('click.myContext',function (e) {
e.stopPropagation();
alert("a");
});
see working example: http://jsfiddle.net/bGBLz/4/

Button click event based on class isn't being fired on button that is dynamically created.

I have a table with dynamically created rows. Each row has a link button that you click on to delete that row. This is the click function here:
$(".deleteButton").on('click', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Some of the buttons are created with one function when the page first loads. Those work, but this other function seems to create a button with the right classes for the event to fire. It creates a link like this.
<a class="deleteButton dButton" href="#">
while the one that works right creates a link like this,
<a href='#' class='deleteButton'>
I have checked in the inspector and it says that the button has the class deleteButton, which is required to fire the event, but it seems to be ignoring it entirely. The Delete Hit never shows in the console.This has really confused me for some time, and I'd appreciate the help anyone can give.
You need to use delegated events for elements that doesn't exist on DOM when you bind event handler
$(document).on('click', '.deleteButton', function(){...}
Where document can be any .deleteButton container that exists at handler bind time.
You can delegate your events.
$(document).on('click', '.deleteButton', function(e){
//do something
});
here is a similar post where I explain the differences between bind live and "on".
How Jquery/Javascript behave on dynamic content updation?
The existing buttons get their event handlers on page load, but the new button is added to the DOM afterwards. You would have to update your JavaScript code, like this:
$(document).on('click', '.deleteButton', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Find more info in the jQuery docs at http://api.jquery.com/on/#direct-and-delegated-events.

jQuery click event triggered multiple times off one click

I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on Stack Overflow to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.
The jQuery, triggered on document.ready
function setupHorzNav(portalWidth) {
$('.next, .prev').each(function() {
$(this).click(function(e) {
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
});
function initiateScroll(target) {
var position = $(target).offset();
$('html, body').animate({
scrollLeft: position.left
}, 500);
}
}
Example HTML
<nav class="prev-next">
Prev
Next
</nav>
In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.
Have I written the code wrongly or is there a bug?
-- Some extra info ------------------------------------------
setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.
if ( portalWidth >= 1248 ) {
wrapperWidth = newWidth * 4;
setupHorzNav(newWidth);
}
else
{
wrapperWidth = '100%';
}
There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.
<nav class="prev-next">
Prev
</nav>
Try unbinding the click event like this
$(this).unbind('click').click(function (e) {
});
You don't need .each() for binding event handlers. Try this instead:
$('.next, .prev').click(function(e){
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
EDIT:
I think it is the way you are attaching the event handler from within the setupHorzNav function that is causing it. Change it to attach it only once from say, $(document).ready() or something.
I have managed to get the situation of multiple event handlers by attaching the event handlers from a function that gets called from event handler. The effect is that the number of click event handlers keeps increasing geometrically with each click.
This is the code: (and the jsfiddle demo)
function setupNav() {
$('.next, .prev').each(function () {
$(this).click(function (e) {
setupNav();
var target = $(this).attr('href');
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});
});
}
setupNav();
See how calling the setupNav() function from the click event handler adds multiple eventhandlers (and the click log message) on successive clicks
Since it is not clear from your question whether you are calling the binding function multiple times, a quick and dirty fix would be:
$('.next, .prev').unbind('click').click(function() {
...
});
What you are doing here is unbinding any previously bound event handlers for click and binding afresh.
Are there no other click bindings elsewhere?
Are you loading the page with ajax?
You could also try this:
$('.next, .prev').click(function (e) {
var target = $(this).attr('href');
initiateScroll(target);
console.log("click!");
e.stopPropagation();
e.preventDefault();
return false;
});

click outside DIV

<body>
<div id="aaa">
<div id="bbb">
</div>
</div>
</body>
$(#?????).click(function(){
$('#bbb').hide();
})
http://jsfiddle.net/GkRY2/
What i must use if i want hide #bbb if user click outside box #bbb? But if i click on div #bbb then box is still visible - only outside.
$('body').click(function(e){
if( e.target.id == 'bbb' )
{ return true; }
else
{ $('#bbb').hide(); }
});
A note of explanation: There are a few ways to do this, either way we need to listen for a click on a parent element, weather it be a direct parent like #aaa or a distant parent like the body or the document. This way we can capture clicks that occur outside of #bbb.
Now that we have that we need the .hide to NOT occur if the user did click inside of #bbb. We can do this two ways
Stop propagation if the user clicks on #bbb. This will make the click event not 'bubble' up to the parent. That way the click event never reaches the parent and so #bbb will not hide. I personally don't like this method because stop propagation will so ALL click events from bubbling, and you may have click events that you would like to bubble to a local parent and not a distant parent. Or you may have listeners delegated from a distant parent, which will stop working if click propagation is stopped.
Check for the #bbb element in the parent listener. This is the method shown above. Basically this listens on a distant parent, and when a click occurs it checks to see if that click is on #bbb specifically. If it IS NOT on #bbb .hide is fired, otherwise it returns true, so other things that may be tied into the click event will continue working. I prefer this method for that reason alone, but secondarily its a-little bit more readable and understandable.
Finally the manner in which you check to see if the click originated at #bbb you have many options. Any will work, the pattern is the real meat of this thing.
http://jsfiddle.net/tpBq4/ //Modded from #Raminson who's answer is very similar.
New suggestion, leverage event bubbling without jQuery.
var isOutSide = true
bbb = documment.getElementById('bbb');
document.body.addEventListener('click', function(){
if(!isOutSide){
bbb.style.display = 'none';
}
isOutSide = true;
});
bbb.addEventListener('click', function(){
isOutSide = false;
});
Catch the click event as it bubbles-up to the document element. When it hits the document element, hide the element. Then in a click event handler for the element, stop the propagation of the event so it doesn't reach the document element:
$(function () {
$(document).on('click', function () {
$('#bbb').hide();
});
$('#bbb').on('click', function (event) {
event.stopPropagation();
});
});
Here is a demo: http://jsfiddle.net/KVXNL/
Docs for event.stopPropagation(): http://api.jquery.com/event.stopPropagation/
I made a plugin that does this. It preserves the value for this where as these other solutions' this value will refer to document.
https://github.com/tylercrompton/clickOut
Use:
$('#bbb').clickOut(function () {
$(this).hide();
});
You can use target property of the event object, try the following:
$(document).click(function(e) {
if (e.target.id != 'bbb') {
$('#bbb').hide();
}
})
DEMO
This will work
$("#aaa").click(function(){
$('#bbb').hide();
});
$("#bbb").click(function(event){
event.stopPropagation();
})​
Becouse bbb is inside the aaa the event will "bubbel up to aaa". So you have to stop the bubbling by using the event.stopPropagation when bbb is clicked
http://jsfiddle.net/GkRY2/5/
OK
* this is none jquery. you can easly modify it to work with IE
first create helper method to facilitate codding don't get confused with JQuery $()
function $g(element) {
return document.getElementById(element);
}
create our listener class
function globalClickEventListener(obj){
this.fire = function(event){
obj.onOutSideClick(event);
}
}
let's say we need to capture every click on document body
so we need to create listeners array and initialize our work. This method will be called on load
function initialize(){
// $g('body') will return reference to our document body. parameter 'body' is the id of our document body
$g('body').globalClickEventListeners = new Array();
$g('body').addGlobalClickEventListener = function (listener)
{
$g('body').globalClickEventListeners.push(listener);
}
// capture onclick event on document body and inform all listeners
$g('body').onclick = function(event) {
for(var i =0;i < $g('body').globalClickEventListeners.length; i++){
$g('body').globalClickEventListeners[i].fire(event);
}
}
}
after initialization we create event listener and pass reference of the object that needs to know every clcik on our document
function goListening(){
var icanSeeEveryClick = $g('myid');
var lsnr = new globalClickEventListener(icanSeeEveryClick);
// add our listener to listeners array
$g('body').addGlobalClickEventListener(lsnr);
// add event handling method to div
icanSeeEveryClick.onOutSideClick = function (event){
alert('Element with id : ' + event.target.id + ' has been clicked');
}
}
* Take into account the document body height and width
* Remove event listeners when you don't need them
$(document).click(function(event) {
if(!$(event.target).closest('#elementId').length) {
if($('#elementId').is(":visible")) {
$('#elementId').hide('fast');
}
}
})
Change the "#elementId" with your div.

Categories

Resources