Why does a bound event activate twice in jQuery? - javascript

I have some HTML:
<div class="form-item">
<a id="listStandardsLink" target="_blank" class="" href="/connect/arisbrowser/standards">Select Standards</a>
</div>
And my javascript is:
$("#listStandardsLink").click( function(e) {
alert("HARD");
// DO STUFF
return false;
});
For some reason, I get TWO alerts when I click it. Any ideas?

If you are not sure where else you are binding the click event try to unbind the event before you bind it.
$("#listStandardsLink").unbind('click').click( function(e) {
alert("HARD");
// DO STUFF
return false;
});

Related

Why does this inline stopPropagation method call not work?

I have this button:
<button
type="button"
onclick='parent.parent.ExecuteCommand(14);event.stopPropagation()'
class="button_air-medium">
<img
id="selectMode"
class="shortcutContant"
src="../stdicons/icon_select.gif">
</button>
As you can see inside onclick attribute I call 2 functions ExecuteCommand and stopPropagation.
The execute command works fine but it seem to me that stopPropagation method is not fired because the element under the button is influenced.
Any idea why stopPropagation method is not working?
There is likely no eventavailable to the inline handler in the browser you are using
You will have an easier time if you do
$(function() {
$(".button_air-medium").on("click",function(e) {
e.stopPropagation();
parent.parent.ExecuteCommand($(this).data("commandnumber"))
// or return false here
});
});
using
<button type="button" data-commandnumber="14"
class="button_air-medium"><img id="selectMode" class="shortcutContant"
src="../stdicons/icon_select.gif"></button>
If you want to stop the image from handling events you could try
$(function() {
$(".button_air-medium").on("click",function(e) {
e.stopPropagation();
parent.parent.ExecuteCommand($(this).data("commandnumber"))
// or return false here
});
$(".button_air-medium > img").on("click",function(e) {
$(this).parent().click();
return false;
});
});
or find where it is handled and edit that handler

JS - Stop function above current function

I have a jQuery click event which adds a class (active) to a dropdown.
In the dropdown there are boxes (with the class generically called box).
Currently the jQuery event fires anytime you click anywhere in the item class, but if you click the box it also closes the dropdown. Thus I am adding an if statement above the addClass part which checks if you clicked a box.
Here's the html:
<div class="trainee-item">
<div class="dropdown">
<div class="box"></div>
</div>
</div>
and here's the JS:
$('.item').click(function(e) {
$('.box').click(function() {
console.log('stop!!!');
});
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
I've tried return (where the console.log('stop!!!!'); currently is, but that only stops the $('.box').click(function() (the immediate "parent" function). I am trying to stop the function above that one
Any help? thanks
One way would be
$('.item').click(function(e){
if (e.target.className=="box"){
e.preventDefault()
return
}
})
$('.item').click(function(e) {
if (e.target.className=="box"){
e.preventDefault()
alert("don't close it!")
return
}
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
.dropdown{display:none;width:100px;height:100px;background:#bbb}
.active{height:120px;}
.item{height:20px;background:#ccc}
.active.dropdown{display:block}
.box{border-bottom:1px solid #999;padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trainee-item item">
<div>Click me</div>
<div class="dropdown">
<div class="box">hi</div>
</div>
</div>
You should separate these into separate click events. You should also delegate them, since you'll trigger both due to event bubbling. It's been a while since I've written jQuery, but from what I remember you should be using .on();, since you can delegate with that method.
I'll leave the delegation as homework for you, but here's how you should be approaching this issue:
$('.item').on('click', function(e, el) {
var $child = $(this).children('.dropdown'),
activeClass = 'active';
$child.hasClass(activeClass) ? $child.removeClass(activeClass) : $child.addClass(activeClass);
});
$('.box').on('click', function(e, el) {
console.log('box clicked');
});

Prevent onclick from firing

I was working around with form submissions in html. Please take a look at below code
<form id="form1">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
$("#btn1").click(function (event) {
alert("event triggered");
if(some_condition == true){
// stop firing onclick method but it always submits the form
event.stopImmediatePropogation(); // not working
event.preventDefault(); // not working
event.stopPropogation(); // not working it's for bubbled events
}
});
function clicked(){ alert("clicked me"); }
</script>
I want to stop clicked() function from firing which is attached to inline onclick attribute. I would like to run my jquery click function and if something goes wrong, I dont want to trigger onclick but it always runs clicked() function. Could any one help me. Any help is greatly appreciated.
The order in which an onxyz handler is called relative to dynamically-attached handlers varies from browser to browser, so your handler may well not run before the original does.
To deal with that, you save and remove the onclick handler:
var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
Then, in your handler, if you want that function to be called, you call it:
clickhandler.call(this, event);
Example:
// Get the button
var btn = $("#btn1");
// Save and remove the onclick handler
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
// Hook up your handler
$("#btn1").click(function(event) {
alert("event triggered");
if (!confirm("Allow it?")) {
// Disallowed, don't call it
alert("stopped it");
} else {
// Allowed, call it
clickHandler.call(this, event);
}
});
// The onclick handler
function clicked() {
alert("clicked me");
}
<form id="form1" onsubmit="return false">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Try event.stopPropagation()
api docs
if condition is true then remove the 'onclick' attribute
if (some_condition == true) {
$("#btn1").removeAttr('onclick').click(function(event) {
alert("event triggered");
//do something
});
}
function clicked() {
alert("clicked me");
}
I am sharing a quick workaround without knowing why you cannot add logic to stop adding "onclick="clicked();" code which you are saying getting automatically added.
I recommend you hide button with id as "btn1". Add style display:none. You donot need on ready function for this but simply add style attribute to the button btn1 or if that is also not possible directly then use jQuery to do that post document ready.
Read :
How to change css display none or block property using Jquery?
Then add a new button to the form using jQuery with id as "btn2" and add register the btn2 click event as well. DO this after form load.
<form id="form1">
<div id="newbut">
<button id="btn1" onclick="clicked();">Submit</button>
</div>
</form>
jQuery("#newbut").html('<button id="btn2">Submit</button>');
$(document).on('click', '#btn2', function(){
// Your Code
});
Refer below url to how to register click event for new button:
Adding click event for a button created dynamically using jQuery
jquery - Click event not working for dynamically created button
Can't you do the condition check and the clicked() logic in one function? i.e
<script>
function clicked() {
if(some_condition == true){
return;
}
alert("clicked me");
}
</script>

How to stop javascript onclick event

I have external link which render image with javascript onclick event.
I need to stop this click event.How can i do this ?
For example:
Html is render by external script:
<div class="demo-link">
<img alt="" onclick="verifylock();" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>
I have tried this with jquery but not get any luck:
$(".demo-link > img").click(function(e){
e.preventDefault();
});
You can remove the onclick value when dom is ready:
$('.demo-link > img').attr('onclick','').unbind('click');
Working Demo
You can always return false from the onClick event handler, call preventDefault, stopImmediatePropagation or other methods, but it would be no use here since HTMLs onclick gets invoked BEFORE jQuery onclick. If you do not want to simply remove the 'onclick' from HTML, you can change it programmatically (and even store it with jquery data() method for future use if needed).
$(".demo-link > img").each(function(e) {
$(this).onclick = function() { // overriding the onclick
return false;
}
});
A working snippet below:
function defaultOnClick() {
alert('Default event handler invoked!');
}
$('.clickable').each(function() {
$(this).data('onClickBackup', this.onclick);
this.onclick = function(event) {
alert('Overriden onclick');
return false;
// if you need to ever call the original onclick, then call below
// $(this).data('onClickBackup').call(this, event || window.event);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="clickable" onclick="defaultOnClick()">Click me!</div>
$(".demo-link > img").click(function(e){
return false;
});
You are writing event on click and calling a function using onclick in img tag. So remove onclick from img tag like.
<img alt="" src="https://example.com" style="cursor:pointer;cursor:hand">
if you want to call a function verifylock() call it from handler for click
Try your own code with return false;
<img alt="" onclick="verifylock(); return false;" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>

Click Node Without Clicking Parent Node

I have a <button> that is wrapped inside of a <div>. I want to be able to click the button without actually clicking on the <div> as well. The <button> needs to remain inside of the <div>.
Heres the code:
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
When i click on the <div> console logs "Div was clicked.".
When i click on the <button> console logs "Button was clicked." AND "Div was clicked.".
How can i click on the <button> WITHOUT a click registering on the <div>?
Any alternatives/workarounds?
Thanks guys.
Add event.stopPropagation() in your button onclick handler.
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='event.stopPropagation(); console.log("Button was clicked.")'>Button</button>
</div>
You can also check the target.id. Here's a small example using jQuery:
HTML:
<div id="parent">
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
jQuery:
$('#parent').click(function(e)
{
if (e.target.id == "parent") {console.log("Div was clicked.")}
});
Fiddle: http://jsfiddle.net/mrnLLvac/
Add the following JavaScript function:
function CancelMouseEvent (Event)
{
Event = Event ? Event : window.Event;
if (Event.stopPropagation) { Event.stopPropagation(); }
if (Event.preventDefault) { Event.preventDefault(); }
Event.cancelBubble = true;
Event.cancel = true;
Event.returnValue = false;
return false;
}
Now use this in HTML:
<button onclick='console.log("Button was clicked."); CancelMouseEvent(event);'>Button</button>
Usually, it is recommended to not use the older method of event binding to HTML. It is recommended to use addEventListener, that way your JS stays in your JS and your HTML is only HTML.
A simple example below:
<div id="wrap">
This is the Div
<button id="button">Button</button>
</div>
<script>
var wrap = document.getElementById('wrap');
wrap.addEventListener('click', handleClick, true);
function handleClick(e) {
e.stopPropagation;
if (e.target.id === 'button') {
// do stuff because button was clicked
console.log('button was clicked');
}
}
</script>
EDIT: why your code didnt work
Your code didn't work because events "bubble" up the DOM (they can also be "captured"...), in your case even if you clicked "button", the following events were triggered:
Button (target) === (bubbling up to its parent) === DIV (its event was also triggered).

Categories

Resources