Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML anchor link - href and onclick both?

I want to author an anchor tag that executes some JavaScript and then proceeds to go wherever the href was taking it. Invoking a function that executes my JavaScript and then sets window.location or top.location to the href location doesn't work for me.

So, imagine I have an element with id "Foo" on the page. I want to author an anchor similar to:

<a href="#Foo" onclick="runMyFunction(); return false;">Do it!</a> 

When this is clicked, I want to execute runMyFunction and then jump the page to #Foo (not cause a reload - using top.location would cause it to reload the page).

Suggestions? I am happy to use jQuery if it can help here...

like image 202
psychotik Avatar asked Aug 28 '09 09:08

psychotik


People also ask

Can a link have href and onclick?

How to make this a tag working with href and onClick? The default behavior of the <a> tag's onclick and href properties are to execute the onclick , then follow the href as long as the onclick doesn't return false , canceling the event (or the event hasn't been prevented).

Can I use onclick in anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

Can we use onclick on link in HTML?

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false. If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

How do you add an onclick event to a hyperlink?

I would generally recommend using element. attachEvent (IE) or element. addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element. attachEvent / addEventListening allow multiple event handlers to be created.


1 Answers

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

like image 186
Amber Avatar answered Sep 19 '22 18:09

Amber