preventdefault not preventing when its inside button - javascript

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/

Related

How do I stop a event propagation?

I understand I need to use the stopPropigation, but how do I get a reference to the event from an onClick function. And Also how do I find out how an event was attached to the element. So I have a simple button like this:
<button class="btn btn-default" onclick="addRoleToReportClicked()">
the function looks like this:
function addRoleToReportClicked() {
$('#addRoleDiv').show();
}
So Simple. And was working fine. Unitl I just did an update of code from work. Now it does show the div, but then proceeds to do other stuff, namely re-load the whole page.
I am using firefox and I see that the button now has a "bubbling" and "DOM0" event handlers. I would love to know how that got there, but more importantly 2 questions:
How do I stop this in the addRoleToReportClicked() function? (I assume that I can stopPropogation, but how do I get a handle to the event?
Is there any easy way to find what code is adding these event listeners? I tried the debug, but that did not show me anything. I don't want to go through 20+ js files and thousands of lines of code to find it. But I do want to hunt down the developer and shoot him.
UPDATE
I tried this:
$("#addRoleDivButton").unbind("click").on("click", function(e){
e.cancelBubble = true;
e.stopPropagation();
e.bubbles = false;
$('#addRoleDiv').show();
});
None of it worked. Taking the idea of a form submition, I noticed that all the other buttons on the page were working fine, but this one was inside a from. So I changed the tag from a "button" to an "a" and it works fine. Someone attached a submit() to every button inside a form tag. How do I stop a submit?
There are a bunch of ways you can stop bubbling, the most popular two ways are -
stop the propagation -
function addRoleToReportClicked(e) {
e.stopPropagation();
$('#addRoleDiv').show();
}
or, unbind the other handlers -
<button class="btn btn-default btn-1">
$(".btn-1").unbind("click").on("click", function(){
$('#addRoleDiv').show();
});
Since you haven't accepted any of the above answers, I'll add this here.
function addRoleToReportClicked(event) {
$('#addRoleDiv').show();
return false;
}
By adding the return false;, it should stop any other functions running. If this or any of the other solutions don't work then there must be something else refreshing the page.
Try and debug it yourself using the chrome or firefox debuggers.
1) the event is passed as argument to the callback function
function addRoleToReportClicked(event) {
event.stopPropagation();
$('#addRoleDiv').show();
}
stopPropagation() will prevent the event from trigger callbacks on parent elements.
You may want to use stopImmediatePropagation() in some cases: I leave to you to look for the difference
jquery: stopPropagation vs stopImmediatePropagation
Note that you may also/instead want to prevent the browser to execute its default actions: (for example a click on a link would also open the link, a click on a submit button would send the form).
In that case you have event.preventDefafult()
EDIT:
Note that if addRoleToReportClicked is invoked because you have
<button class="btn btn-default" onclick="addRoleToReportClicked()">
Then the event object is not passed to the function
You may remove the onclick attribute.
Then if you need to catch the click on the button use Jquery's on('click')
2) Google Chrome (Dev Tools) tells you what event listeners are attached to an element (just right-click and inspect the element).
AFAIK it doesn't tell you where on the code the event listener were set up.
But if you perform a global search on your sources for the name of the event listener you should find it.

preventDefault function: What is the real utility?

I'm newbie in jquery and saw a piece of code with something strange given the functionality of a method, the "preventDefault". Well, to test, i created a test page and made two functions with "preventDefault" inside of it.
I have two questions on the same subject, i hope you can answer me.
$(document).ready( function( ) {
$('a').click( function( event ) {//Func 1
event.preventDefault( );
});
$("#ok").click( function( event ) {//Func 2
event.preventDefault( );
alert("Wut");
//...
});
});
1- Why, in the second function, the "alert( )" runs even if i comment "event.preventDefault( );" and the first function does not happen the same? If i comment "event.preventDefault();" in the first function, the link doesn't work!
I found it strange because regardless of the method "event.preventDefault();" whether or not commented in the second function, the "alert" works the same way. I think even what comes after "alert" would run.
2- What is the real utility of this method, "event.preventDefault ();"? Why, in the second function, it seems to be useless. Can you give me some example of when it might be useful?
Thanks!
The purpose of preventDefault is to prevent the browser's default action related to the event. Your alert isn't the browser's default action, and is unaffected. Following a link is the browser's default action, and so preventing the default prevents following the link.
preventDefault is crucial in many situations. For instance, when handling a form's submit event, we need preventDefault (directly or indirectly) if we do client-side form validation and the form isn't valid; otherwise, the browser would submit the invalid form.
(I said "directly or indirectly" above because jQuery handles the return value of event handlers in a special way: If you return false, it calls preventDefault and stopPropagation for you.)
It prevents the default action of the control. If it a link, it stops the link being followed. If it is a form submission, it prevents the form from being submitted.
It doesn't interact with other JS event handlers on the same element.
Examples of situations where you might use it:
Stopping the browser following a link because you have used Ajax and pushState to load the content and update the URL
Stopping the browser from submitting a form because you have tested the data entered and found a problem with it
The .preventDefault() function prevents the browser from carrying out the normal implicit behavior of an interactive element. If you click on an <a> tag, then apart from anything your JavaScript does the browser will attempt to follow the "href" value and reload the page. That's the "default" behavior that the function name refers to.
Your alert() runs because .preventDefault() has nothing to do with the code in your event handler. If you want to "abort" an event handler, you'd just return from it.
Note that jQuery also gives you .stopPropagation() and .stopImmediatePropagation() to cancel the process of event bubbling. Those also have no direct effect on the code in your event handler.
event.preventDefault() disables the default behaviour of the event. In case of an link the redirect. It does not effect your own code, in this case the alert() call.

jQuery Adds Extra '#' to URL?

I noticed sometimes that when I use jQuery, a extra '#' gets added to the end of my URL after a jQuery function is called. For example, the URL 'www.mywebsite.com' will change to 'www.mywebsite.com/#' once a jQuery function is initialized. The same for 'www.testsite.com/users.php', is changed to 'www.testsite.com/users.php#'.
Why does jQuery add the '#'?
If your function is running from a link onclick, you need to use event.preventDefault()
See http://api.jquery.com/event.preventDefault/
Probably you're getting this when handling a click event. If you don't want that happens, just add event.preventDefault() or return false at the end in event handler function.
Usually this is because you have a dummy link with a jQuery click handler. It's common to see links with an href of # that are only used to trigger some JavaScript.
Go
Resolve this easily by making a habit of calling e.preventDefault() in your click handlers:
$(function() {
$(".button").click(function(e) {
e.preventDefault();
...
});
});
You can also use return false, but that has the added effect of stopping event propagation. I like to add e.stopPropagation() explicitly if I also want that effect. It makes the code and it's intended effect more explicit and clear for future developers (or myself in 6 months).

Multiple OnClick JQuery events firing

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

JQuery: Convert onClick attribute to to jQuery click

I have a webpage with 100+ hyperlinks that all have the onClick and href attribute set. This works for the most part but I've run into the issue where browsers like IE7 use the href attribute over the onClick attribute. I need the onClick attribute to be the default so my function will load on click. I figured I could easily do this using jQuery and setting the click event to the onClick attribute value but I'm not having any luck, how would I go about this? Right now the code below sets TONS of click events to a single hyperlink. When I click a hyperlink I can watch the GET events sent multiple times for the hyperlink.
$("a[href*='/RightSizeOption/NewForm.aspx']").click(function() {
OpenPopUpPage($(this).attr('href'), RefreshPage);
return false;
});
Doesn't seem to make sense, unless that exact click handler is actually being bound multiple times. A better way of binding clicks is with delegate (also using preventDefault instead of return false for good measure):
$('#myParent').delegate("a[href*='/RightSizeOption/NewForm.aspx']", "click", function(event) {
event.preventDefault();
OpenPopUpPage($(this).attr('href'), RefreshPage);
});
#myParent is any ancestor element that is not expected to get destroyed; could be a wrapper div or 'body' even, though it's better to pick the closest common ancestor that never gets destroyed.
But what worries me is the multiple binding; if your sample code is within a function, that function is being fired multiple times, for example.
I'm also not certain about the "RefreshPage" that you're passing to OpenPopUpPage. I'd have to see what OpenPopUpPage does to even hazard a guess.

Categories

Resources