Multiple OnClick JQuery events firing - javascript

I have a page with div and a button on it. I have added onClick event to both of them. Now when I click the button on the div the onClick of the div is also being executed. Is there any way that I can avoid this?
Thank You,

Try this, pass the event as parameter to your onclick event and call
event.stopPropagation();
event.preventDefault();
Your onclick event assignment should be:
$(button).click(function(event) {
// script here
event.stopPropagation();
event.preventDefault();
});

In your click handler you might want to use "stopPropagation" for example:
$("button").click(function(e) {
// handle this event
// ...
// don't pass this event up to parent handlers
e.stopPropagation();
} );
There's also a related function that you might want to read about called "preventDefault" which tells the browser not to do what it normally does automatically (e.g. submit a page when a submit button is clicked)
See also:
https://developer.mozilla.org/en/DOM/event.stopPropagation
http://api.jquery.com/event.stopPropagation/
What's the effect of adding 'return false' to a click event listener?
http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

in the listener for the link element, you can put e.stopPropagation(), which should fix it (if you're using event bubbling).
If you aren't using jQuery, make sure you set the useCapture parameter of addEventListener() to False info - MDN; you want to be sure you know which direction your events are moving through the DOM (you want them to bubble).

You need to prevent the button onClick event from bubbling to the Div. So basically at the end of your onClick function for the button, once you have done all you logic, you need to call event.stopPropagation()

If none of the above work, try out:
$("button").click(function(e) {
e.stopImmediatePropagation();
});

Related

I can't prevent a button click event on JQuery

I have a button that clears a list, the click on this button shows a dialog that asks for validation (Yes/No). What I want is to disable the "Clear" button after clearing the list (Click on Yes). Here's my code :
$('#clearBtn').click(function() {
$('#alert5').show();
$('#bg').show();
$('#Yes').click(function(){
$('.list1').empty();
$('#clearBtn').disable(true);
$('#clearBtn').click(function(e){
e.preventDefault();
});
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
});
the preventDefault() function doesn't seem to work.
First never nest event handlers.
$('#cleatBtn').click(function () {
$('#alert5').show();
$('#bg').show();
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
If you just want to disable then use the following syntax
$('#cleatBtn').attr('disabled', true);
Remove the innermost event completely.. That is not required.
Use on to bind the events, if you want the button to be enabled but turn off the event handler using off
One more option you have is to apply a class to the button when you press yes and execute the code only when the class is not present.
$('#cleatBtn').click(function () {
if( !$(this).hasClass('active')) {
$('#alert5').show();
$('#bg').show();
}
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$('#cleatBtn').addClass('active');
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
To disable a button, call the prop function with the argument true on it:
$('#cleatBtn').prop("disabled", true);
e.preventDefault(); is the correct way of cancelling events. Some older browsers also expect a return type of false. Which I think will cause jQuery to call preventDefault()?
Here's a good answer: What's the effect of adding 'return false' to a click event listener?
I think your structure looks a bit odd. you don't need to attach click events within a click event.
Just attach them all separately on document.ready events. At the moment they are nested, then go back to trying to cancel your event. The dom tree might be confused by the way the events are nested.
Hope that helps.

Prevent click event on the clicked element?

I have a click event on the body of my document:
$("body").on('click.findElem', function(e) {
e.stopPropagation();
e.preventDefault();
self.hinter(e.target);
return false;
});
It basically catches the clicked target and does something to it. However, there are some targets that already have a click event on them, and they prevent my click from being executed at all. How do I overcome that issue? I tried unbinding it, but the click doesn't even work at all to actually execute the unbinding.
e.stopImmediatePropagation() does the job, but only if your handler executes before whatever other handler exists.
Unfortunately there is no way to insert your own handler in the first position - but you can use this nasty hack if the other handlers were bound using jQuery, too: How do you force your javascript event to run first, regardless of the order in which the events were added?
If you really need this you might want to bind an event handler in capture mode using the native DOM API: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Capture handlers are triggered before bubble handlers (which are used by jQuery and most other scripts) so that way you have very high chance to execute your handler first.
try this and see demo
$( "body" ).on( "click", ".clickme:not(.clicked)", function( event ) {
$(this).addClass('clicked');
alert('here');
});
i tend to not use on and stick with the bind/unbind combo.
i have some pages that reload partial content and then has to rebind the events.
i tipically do something like this
$(".theobjectsiwant").unbind("click").bind("click", function() {
alert('hi there');
});
If you want/have to stick with the on() function, you shouldn't mix on() with unbind() and try a similar approach with .off("click").on("click")
Check here for a sample http://api.jquery.com/off/

preventdefault not preventing when its inside button

I could not make preventdefault to prevent action. I apologize if the answer is too easy but I simply cant find the error. why is it not preventing from entering the link? jsfiddle given below.
http://jsfiddle.net/zwY5p/34/
$('#theForm').click(function(e) {
event.preventDefault();
alert('FORM!');
});
e != event
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
The parameter passed to the handler function is what you need to execute preventDefault on. In your code, you are passing e but calling preventDefault on event.
preventDefault prevents the default browser action. It does not cancel the inline JavaScript, since that runs first. If you have to override that, just remove it (no event listener necessary):
$('#theForm').removeAttr('onclick').
your event parameter name e and the variable you are using event are different,
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
Other than the errors pointed out on other answers there's another small issue, specifically in your markup declaration:
<!-- Use either the closing tag or the slash (/) in the opening tag -->
<button id="theForm" onclick="location.href='http://www.example.com'" />
go to google
</button>
On the topic, you have two different handlers attached to the button element, they are both handling the click event but they are still different and separate things. jQuery won't know about the handler defined in the markup:
var btn = document.getElementById('theForm');
jQuery._data( btn, "events" );
will return an array with a single element which is the handler added via jQuery.
Now you have to re-evaluate the need of two different handlers for the same element and event and apply conditions. Do you really need to do it this way?
You're using 2 'click' events.
You end up using preventDefault once, and it's used after the 1st click event has ran.
If you make your button an href, then your preventDefault will be working.
It will also make more sense, as the JS will be separated from the HTML markup.
Also, of course you must use the same parameter name. (function(event), with event.preventDefault for example).
If you are passing "e" as an event to the function then you should prevent the default action only for that "e" that you have passed and not for "event".
$('#theForm').click(function(e) {
e.preventDefault();
alert('FORM!');
});
jQuery preventDefault() method: http://api.jquery.com/event.preventDefault/

How to make all page elements not to react on clicks

I'm trying to make an extension with 'pick' functionality: letting the user click on any element on the page and see the xpath for it.
However, to make it usable I have to prevent the element from reacting on clicking: I don't want clicking on hyperlinks to forward me to another page, buttons to submit forms, etc., etc.
How would I do that?
UPD: I need it only for Chrome
The cleanest way in my opinion would be to bind one event handler to body in the capturing phase and prevent the event from propagating/the default behavior.
You can get a reference to the clicked element with event.target:
document.body.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
console.log(event.target);
}, true);
The advantage is that this event handler will be the very first that is triggered, no matter which other event handlers are bound to elements in the page (unless of course the page binds a similar event handler to body, but usually event handlers are bound in the bubbling phase).
For more information see quirksmode.org - Event order and MDN - addEventListener.
DEMO
For a CSS only solution:
* {
pointer-events: none;
}
Try this
$('body *').on('click',function(e){
return false;
});
In your click event handler make sure you either call preventDefault() in the event object, or return false from your function. For example:
function myClickHandler(e) {
e.preventDefault() // e is the event object
// Do your click stuff here
.
.
.
return false; // not required if you've called e.preventDefault()
}

how to select the rest of a div?

i got a problem
<div id='parent'>
<div id='child'>
</div>
</div>
what i want is when the child is clicked addClass,and when the rest of parent is clicked removeClass,so when i try to do
$('#child').click(function(){
$(this).addClass();
})
$('#parent').click(function(){
$('#child').removeClass();
})
its not working i think its because the child is actually inside the parent,so when the child is clicked the parent clicked right?
so how can i do that?
try this:
$('#child').click(function(evt){
evt.stopPropagation();
$(this).addClass("myClass");
});
You could use event.stopPropagation to prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('#child').click(function(e){
e.stopPropagation();
$(this).addClass();
});
Several users have already suggested a good solution - here's an explanation of why it works:
When you click an HTML element (actually a DOM object...), the click event "bubbles" all the way up to the root element. For example, a click in #child also triggers a click in #parent, as you expected.
To stop this behavior, you need to call .stopPropagation() on the click event - that will tell the browser that you do not want the event to propagate, but keep it "local". Basically, when you've handled it here, you're done with it and don't want to see it again.
Conveniently, jQuery event handlers take the event as the first argument, so if you assign any function with the signature function (e) { ... }, you can stop event propagation by e.stopPropagation(); as others have suggested. In your case, you want
$('#child').click(function(e){
$(this).addClass();
e.stopPropagation();
});
$('#parent').click(function(){
$('#child').removeClass();
});

Categories

Resources