HTML <a> tag event order - javascript

I have a basic question regarding a tag in HTML.
Say that I've got some HTML like this
Do some work
When a user clicks on an anchor link (Do some work) which event will trigger first?
I mean whether doSomething() or href goes first.

doSomething() go first.. and if it returns false or is prevented, then the anchor link is not called.

This is what will happen:
The event will fire
the page will redirect.
But don't take my word for it, go test it out for yourself. I even got it started for you:
http://jsfiddle.net/WDdZS/
this is the simple code I used
function doSomething(){
alert("hello");
}
I added the return false, mentioned in other answers so you can see it in action. I didn't know about that actually, so always good to learn something new.

The JavaScript will execute first.

Related

Why isn't click event firing in this simple jsfiddle demo?

I'm trying to create a little demo on jsfiddle, but when I click the toggle button, the click event isn't firing, it says myclick is not defined.
I have looked at other answers which mention the No wrap solution, but I don't see such configuration option in jsfiddle right now.
The jsfiddle: https://jsfiddle.net/5j9qgbxa/4/
Change the load type to No wrap -bottom of the <body>
Here is the Demo
It seems that the javascript with type onload will create the javascript in the beginning of your jsfiddle as followed:
window.onload=function(){
function myclick(){
alert("myclick");
}
}
<YourHTML>
In which case he will not recognize myclick() as this is created later on in the HTML and is not triggered with onload. What you can do to avoid this is as you can see in this jsfiddle: https://jsfiddle.net/cqL9t8mh/1/
What I did here is, delete the onclick="myclick" in your button and replace it with and ID 'btnToggle'. Afterwards in the javascript section you can add an addEventListener of the type click on the ID 'btnToggle' to trigger your myclick function.
Also what you asked in the commands of previous answer is following:
This will make it so your code layout well be like:
<YourHTML>
function myclick(){
alert("myclick");
}
In which case your HTML is first created before your function and it is no longer in an onload so it will now be triggered every time you click your button.

How to disable e.preventDefault for some elements

I am using a OnePage template of bootstrap, I can not click a link, or can not switch a radio button, someone says I am using e.preventDefault()
Open this page http://abi.maxinrui.com/, you will see what I mean when you click "Click me" on that page.
I check the js file, there are lots of e.preventDefault() and I don't know how to modify them.
Is there a way to disable e.preventDefault()?
I want to have some hyperlink to another websites in my OnePage templete, so here is what I am think: I give some particular elements an ID or class, then I write some js, to disable e.perventDefault() only for these elements.
Does anybody know how to do that?
Thanks!
If you're using jQuery to handle your events, then it's possible!
First, a fiddle (shell for full effect): http://fiddle.jshell.net/UN5WE/show/
Here's the actual fiddle to edit: http://jsfiddle.net/UN5WE/
Basically, we're modifying jQuery's Event object, and specifically, the preventDefault method found on the prototype. We maintain a reference to re-enable preventDefault.
EDIT
For your specific use case, here's a way to disable preventDefault (based on a class). Just run this script after jQuery has loaded:
jQuery.Event.prototype.preventDefault = (function(){
var originalFunc = jQuery.Event.prototype.preventDefault;
return function(){
if($(this.target).hasClass('disableDefault')) {return;}
originalFunc.call(this);
}
}())
Prior to calling preventDefault, this will check to see if the target has a disableDefault class. If it does, it returns immediately (allowing the default to happen). To test your page, copy that code into your console and then run: $('h1').addClass('disableDefault').
I don't think is possible, or at least not on an easy way that i can think of, you can unbind the handlers if they were setted using bind, but that will also remove any behavior that they have, but you can use a workaround, add a new event handler for your links, i recommend that you add a special class to external anchors and then get the href attribute from it and open a new tab using window.open like this:
http://jsfiddle.net/yV78E/2/
The html
Hey
The js
// Similar behavior that might be on your site
$('a').click(function(e){
e.preventDefault();
// some code
});
// Use the code below as a workaround
$('.externalLink').click(function(e){
var targetLink = $(this).attr('href');
window.open(targetLink, '_blank');
});
You only need the second part of the script above, since the first one is just to emulate your problem.

Prevent a standard a href/jquery click combo from appending # to the url?

I have a standard link setup that fires an event via jquery when clicked
Click Me
All that works great, except that when the pseudo URL is clicked, it appends a hashtag (#) to the url. This hashtag affects how my page reloads if the user decides to refresh the page later on, so i'd like to not have the hashtag appended to the url.
is this possible while still allowing my normal jquery to fire?
Thanks!
You should either return false; from the event handler of A tag
Or, use
Click Me
For those who thinks javascript: void(0) is bad practice
If you use href='#', you must take care of two things
// one
function fn() {
// code
return false;
}
// two
click
And if you forget and just write onclick="fn();" it won't work
Another thing why I used javascript: void(0); is, if the function encounters/throws an error, it wont return false
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
In end of the you click function, use:
return false;
smartass anwser: use a button.
alternative: you must make sure to trigger the preventDefault in youre jQuery event handler
$("dosomthing").click(function(e){
//make magic happen
e.preventDefault()
})
this works on html forms thats submitting and such.
note on the button thing
it is best pratice to only use a tags for link (somthing that changes the url) and buttons for other sorts of interactions.
search bots and other web crawlers expect a tags to link to a other html document (hyperlink) and up to and including html 4. or to a other point in the current document.
Does it need to be an href at all? you could do:
<span class="dosomething">Click me</span>
.
.dosomething{cursor:pointer}

<a href="javascript:foo(this)"> passes Window, I want the tag element itself

I expect this to print "a" because when I call foo(this), the argument seems to be the link tag.
<script type="text/javascript">
function foo (e) {
alert (e .tagName);
}
</script>
click
Instead, it prints "undefined". If I alert(e) it says "object Window". How do I make foo know which element launched it? Without passing/looking up ids.
You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.
click
You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.
It is better to attach the event with Unobtrusive JavaScript
You can do this directly too
click​
The this object is not handled the same in all browsers. This is one of the many items that libraries like Prototype and jQuery try to normalize. That said, however, most browsers will pass the appropriate this during on onclick handle (rather than the href) as many other answers have pointed out. If you want to handle the this appropriately, you'll need to do things like those detailed in this question.
click
function foo(obj) {
alert(obj.tagName);
}​
Don't call the element e it's a standard for the event object.
JSfiddle DEMO

'OnClick' interrupts my hyperlink

I have an <a> tag that contains a span. The span has javascript attached to it that does something. As a result, when the span is clicked, the javascript runs, but the <a href> is ignored and it doesn't navigate to it.
Is there a way to make it continue to navigate as normal?
<a href='http://www.google.com'><span>some text</span></a>
the click event is actually registered some other way than onclick, my question title is a bit misleading.
Hovering over the link puts the URL into the status bar as you'd expect, just clicking it does nothing.
The javascript is simple return true; at the moment while I try to figure it out.
I suspect as the javascript is in the span and not the a that it gets confused about how to propogate back up to the href once the javascript is done.
I'm afraid I don't know how it's bound, because it's some bizarre third party component.
I suspect as the javascript is in the span and not the a that it gets confused about how to propogate back up to the href once the javascript is done.
Yes. If your onClick handler is on the span, the browser can't read the hyperlink's href attribute. If the link has an id, you can do :
function onclick()
{
//Do your things...
var link = document.getElementbyId('your_link_id').href;
window.location.href = link;
return true;
}
Your javascript is probably returning a value that is non-true (a value that evaluates to boolean false). The simple solution is to add a return true statement to the end of the function/code that runs when the link is clicked.
If you're using jQuery, make sure you don't return false in your event handler. That will override the defaults.
If not: you may need to explicitly code what you want your link to do after your JS:
click here
This will execute a function, then redirect the window to the proper location.

Categories

Resources