How to stop javascript onclick event - javascript

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>

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

Preventing href in <a></a> from executing via Javascript

So I have this following code in my HTML:
<li class="" id="toolbar_section"><a id="toolbar_section_child" href="#foobar" onclick="return toolbarSetSection(this);" data-toggle="checkpoint">foobar</a></li>
And written in my Javascript is:
<script type="text/javascript">
function toolbarSetSection(event){
//some logic which leads to
return false;
};
</script>
However, the href still executes... I have checked many similar topics with answers like event.preventDefault(); but they don't help me either.
In your HTML you should change onclick="return toolbarSetSection(this);" to onclick="toolbarSetSection(event);", and then have event.preventDefault(); in your javascript function.
Your full code would be:
<li class="" id="toolbar_section"><a id="toolbar_section_child" href="#foobar" onclick="toolbarSetSection(event);" data-toggle="checkpoint">foobar</a></li>
and
function toolbarSetSection(event) {
event.preventDefault();
return false;
};
return false should usually work, but maybe there is an error in your toolbarSetSection function.
Calling event.preventDefault() should usually work, too. However in your case you expect the function to be called with event as first parameter, while your HTML code calls onclick="return toolbarSetSection(this);" with the link object as first parameter. Maybe you wanted to call toolbarSetSection(event); instead.
HTML
<ul>
<li class="" id="toolbar_section2"><a id="toolbar_section_child" href="#" onclick="toolbarSetSection()" data-toggle="checkpoint">foobar</a></li>
</ul>
js
function toolbarSetSection()
{
alert('started');
event.preventDefault();
alert('weee');
}
jsfiddle so you cannot say it is not working :) : https://jsfiddle.net/rgoopw18/1/
a better way to get the expected behavior without adding onclick on the tag
<script>
document.getElementById('toolbar_section_child').on('click', function(e){
e.preventDefault();
})
</script>
Assuming you have a unique id for the a tag.
EDIT
for dynamically created elements use event delegation
document.addEventListener('click',function(e){
/*
if(e.target && e.target.id == 'toolbar_section_child'){
e.preventDefault();
}
*/
// using a common class name
if(e.target && e.target.className.split(" ").indexOf("toolbar_section_child") != -1){
e.preventDefault();
}
})

stopPropagation() not working

I want to stop bubbling when click on image. I cannot set javascript void on href as it is required. I have used stopPropagation but it is not working.
function showurl(e){
e.stopPropagation()
window.location="http://www.yahoo.co.in"
}
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" onclick="showurl(event)" />
</a>
As this was a jQuery question I would suggest never using onclick attributes. They only support a single handler and they are are "ugly" (read: harder to find and maintain) :)
$('img").onclick = function(e) {
e.preventDefault();
window.location="http://www.yahoo.co.in";
}
or
$('img").onclick = function() {
window.location="http://www.yahoo.co.in";
// return false here does the same as e.stopPropagation() and e.preventDefault();
return false;
}
As this handler applies to all img elements, you may want to data-drive the whole thing (using attributes) like this:
Put the target url in the image as a data-url attribute
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png"
data-url="http://www.yahoo.co.in" />
</a>
And code-wise:
$('img").onclick = function(e) {
// See if image has a data-url attribute
var url = $(this).data('url');
if (url){
window.location=url;
// only prevent default if it was an image with a link attribute
e.preventDefault();
}
}
I would suggest binding it from JS, even with a basic onclick then use return false; or use preventDefault. (demo)
document.getElementsByTagName("img")[0].onclick = function() {
window.location="http://www.yahoo.co.in";
return false;
}
HTML
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" />
</a>

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).

Why does a bound event activate twice in jQuery?

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;
});

Categories

Resources