How to stop default link click behavior with jQuery - javascript

I have a link on a web page. When a user clicks it, a widget on the page should update. However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.
This is what the link looks like:
Update Cart
This is what the jQuery looks like:
$('.update-cart').click(function(e) {
e.stopPropagation();
updateCartWidget();
});
What is the problem?

e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable,
without stopping further propagation
of the event.

$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.

You want e.preventDefault() to prevent the default functionality from occurring.
Or have return false from your method.
preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

You can use e.preventDefault(); instead of e.stopPropagation();

This code strip all event listeners
var old_element=document.getElementsByClassName(".update-cart");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?

Related

It scrolls to the top of the page after clicking

I have this code to switch a switching button image:
$("#invio_scatola_on, #invio_scatola_off").click(function(){
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});
when it is executed, the browser goes to the top of the page. why?
You probably need to prevent the default action of whatever element you click:
$("#invio_scatola_on, #invio_scatola_off").on('click', function(e){
e.preventDefault();
$("#invio_scatola_off, #invio_scatola_on").toggle();
});
Based on the few information that you've provided, if the browser is scrolling to the top, it means that you need to prevent its default behavior.
Check to see if the browser is appending "something" to the current URL...
You can prevent that like this:
$("#invio_scatola_on, #invio_scatola_off").click(function(event){
// prvent default behavior
event.preventDefault();
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});
See the jQuery event.preventDefault() for more information on how it works.
I can only guess, because you didn't post your html code. Most probably your two elements are links with href="#". After you click handler the regular action is fired, navigating to the anchor # on your site (which is the top).
Try:
$("#invio_scatola_on, #invio_scatola_off").click(function(event){
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
event.preventDefault();
});
and see if that helps. More on event cancelling with jQuery here:
http://api.jquery.com/event.preventDefault/
I think you binded the click on anchor tags with href as # so for that you can use preventDefault() of javascript like :
$("#invio_scatola_on, #invio_scatola_off").click(function(evt){
evt.preventDefault();
$("#invio_scatola_off").toggle();
$("#invio_scatola_on").toggle();
});

does e.stopPropagation() in jquery works on anchor tag

i want prevent eventpropogation from element inside an anchor tag i m trying to use e.stopPropagation(); it doesn't seem to work is it possible or i m just wasting time please help me out of here
javascript is:
$(document).ready(function(){
$('.alink .p').click(function(e){
alert("hi");
e.stopPropagation();
});
html is :
<div>
<a href="http://google.com" class="alink" >Google links
<p class="p">Another Links to prevent default</p>
</a>
</div>
thanks for your precious time
event.stopPropagation() stops passing the event to handlers further away in DOM structure from the element, on which originally event was triggered. It does not, although, prevent action that has already been triggered.
You should use event.preventDefault() to stop mentioned above default action.
Sources:
event.preventDefault()
event.stopPropagation()
Description
It will not stop any default behaviours (such as link clicks) and you might want to consider using event.preventDefault() in addition to this method.
event.stopPropagation() is only for event handlers, not default behavior.
event.preventDefault() If this method is called, the default action of the event will not be triggered.
You had some spelling errors in your script and its document not "document".
Check out the Sample and this jsFiddle Demonstration
Sample
$(document).ready(function(){
$('.alink, .alink > .p').click(function(e){
e.preventDefault();
e.stopPropagation();
alert("hi");
});
});
More Information
jQuery - event.preventDefault()
jQuery - event.stopPropagation()
try this
$(document).ready(function(){
$('.alink .p').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
alert("hi");
return false;
});
});
you should use- e.preventDefault() to stop default behavior. stopPropagation is used to stop event bubbling.
You've missed enclosing brackets here, didn't you?
$('document').ready(function(){
$('.alink .p').click(function(e){
alert("hi");
e.stopPropagation();
});
Fix brackets and then use e.preventDefault() instead.

What is the argument for?

$(document).ready(function(){
$('#something ul a').click(function(e) {
...
...
e.preventDefault();
})
});
what is the e for and the e.preventDefault mean so i can understand what is happening here
The e argument is the event object.
It contains information about the click event.
For more information, see the documentation.
The preventDefault() method prevents the borwser's default action for the event.
In this case, it will prevent the browser from navigating to the link.
It's preventing the default action of the event, e.g. going to the URL, or scrolling the page to the #location in the href.
The first argument to any event handler in jQuery is the event object itself.
e is the event object, and prevent default is one of its functions.
E is event and preventDefaults prevents browser from performing a standard operation in response to such an event. For instance if this is a click event on a link, preventDefaults whould prevent browser from redirecting to a linked page.
The preventDefault() method prevents the borwser's default action for the event.
In this case, it will prevent the browser from navigating to the link.
shareedit

disable all click events on page (javascript)

Whats the easiest way to temporarily disable all mouse click/drag etc events through javascript?
I thought I could do document.onclick = function() { return false; }; ...etc, but that's not working.
If the objective is to disable click on the whole page then you can do something like this
document.addEventListener("click", handler, true);
function handler(e) {
e.stopPropagation();
e.preventDefault();
}
true argument in addEventListener would ensure that the handler is executed on the event capturing phase i.e a click on any element would first be captured on the document and the listener for document's click event would be executed first before listener for any other element. The trick here is to stop the event from further propagation to the elements below thus ending the dispatch process to make sure that the event doesn't reach the target.
Also you need to stop default behavior associated with event target elements explicitly as they would be executed by default after the dispatch process has finished even if the event was stopped propagating further from above
It can be further modified to use selectively.
function handler(e) {
if(e.target.className=="class_name"){
e.stopPropagation();
e.preventDefault();
}
}
handler modified this way would disable clicks only on elements with class "class_name".
function handler(e) {
if(e.target.className!=="class_name") {
e.stopPropagation()
}
}
this would enable clicks only on elements with class "class_name".
Hope this helped :)
Dynamically disable all clicks on page
let freezeClic = false; // just modify that variable to disable all clics events
document.addEventListener("click", e => {
if (freezeClic) {
e.stopPropagation();
e.preventDefault();
}
}, true);
I often use it while loading or to avoid user to accidentally clic twice on an action button. Simple and performance friendly :)
Please check this working example
Alternative CSS way
Another one that I really like because of the visual feedback the user have:
/* style.css */
.loading {
cursor: wait; /* busy cursor feedback */
}
.loading * {
/* disable all mouse events on children elements */
pointer-events: none;
}
A simple example to dynamically add the .loading class:
const elm = document.getElementById('myElm')
elm.classList.add('loading')
myAsyncFunction().then(() => elm.classList.remove('loading'))
If you want absolutely nothing draggable/clickable, disabling typing in input fields etc, I'd consider showing a absolutely positioned transparent div over the entire page, so that every click will be on the div, which will do nothing. That will grant you swift and neat switching on and off of this click-disabler, without having to register heaps of listeners
The winning answer works well, but if you had pass the capture true boolean value, at the moment you want to remove the listener, you have to pass the exact same value. Otherwise, the listener removal will not work.
Example:
listener addition
document.addEventListener('click', DisableClickOnPage.handler, true);
listener removal
document.removeEventListener('click', DisableClickOnPage.handler, true);
Doc: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
window.addEventListener("click", (e) => {
e.stopPropagation();
e.stopImmediatePropagation();
e.preventDefault();
}, true)
If we added a listener to document instead of window anyone can add a listener to window and it works. Because of document child of window and its events trigger always after window events.
We use 3 method of Event object.
stopPropagation for prevent all capturing and bubbling
stopImmediatePropagation for prevent same listeners (e.g. another window click listeners)
preventDefault for prevent all user agent event (e.g anchor href or form submit)
If onclick = null has been executed how to revoke the onclick event to normal functioning.. or
Link text
<script type="text/javascript">
function yourFunction(anchor)
{ if(anchor.disabled) return;
/* Your function here */
}
</script>
This article would probably be useful:
http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/
One part in particular is a recursive function that removes all click events. Remember that jQuery will remove click events IF the click event was created using jQuery. the function given in the article will remove both those created with jQuery and those that were not. The function given is this:
function RecursiveUnbind($jElement) {
// remove this element's and all of its children's click events
$jElement.unbind();
$jElement.removeAttr('onclick');
$jElement.children().each(function () {
RecursiveUnbind($(this));
});
}
You would call the function like this:
RecursiveUnbind($('#container'));
That function takes a jQuery object parameter, but you could easily change it up to pass a string as the name of the ID for the element, or however you think is best.
To prevent the default behavior of an event, use event.stopPropagation() and event.preventDefault() in your event handler. And don't forget, return false; is another method for indicating that you want to cancel the default action...
The Event property returnValue indicates whether the default action for this event has been prevented or not. It is set to true by default, allowing the default action to occur. Setting this property to false prevents the default action. (Source: MDN Web Docs: Event.returnValue.)
Typically, we return a value from any function when it has any meaningful or useful purpose -- return false to cancel an event is meaningful because it indicates a failed event, and it's useful because the event-handler uses it.
For greatest cross-browser compatibility, remember to return false;...
document.addEventListener("click",handler,true);
function handler(e){
e.stopPropagation();
e.preventDefault();
return false;
}

Multiple events firing from single action

I have an onclick event attached to a region in my page that causes a certain action to fire when the user clicks in it (naturally). I recently added an image to that region. When the user clicks on that image, I want another action to occur, and I do NOT want the action associated with the entire region to occur. However, I find that both events are, in fact fired when one clicks the image. How do I suppress the region-wide action when the image is clicked?
The issue you are running into is known as event bubbling. The click event of the image bubbles up to all parent elements of that node. You want to cancel bubbling.
The best way to do this that works across all browsers is by using a JavaScript framework. jQuery has a very simple way to do this. Other frameworks have similar mechanisms to cancel bubbling, I just happen to be most familiar with jQuery.
For example, you could do something like this in jQuery:
$('img').click(function () {
// Do some stuff
return false;// <- Cancels bubbling to parent elements.
});
Darit is correct, you need to stop the event from bubbling (propagating):
function imgEventHandler(e) {
// ^notice: pass 'e' (W3C event)
// W3C:
e.stopPropagation();
// IE:
if (window.event) {
window.event.cancelBubble = true;
}
}
In the event handler for the image do
event.cancelBubble = true;
and then at the end do
return false;

Categories

Resources