Including both href and onclick to HTML <a> tag
Asked Answered
B

7

172

If I have this element:

<a href="www.mysite.com" onClick="javascript.function();">Item</a>

How can I make both href and onClick work, preferably with onClick running first?

Barkeeper answered 14/2, 2013 at 3:56 Comment(3)
Check this Set A tag link in HTML using JavaScriptTunny
This one may help, It works for me : https://mcmap.net/q/144861/-html-anchor-tag-with-javascript-onclick-eventChrysolite
@Tunny what is your link about, does it help?Ass
F
291

You already have what you need, with a minor syntax change:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

The default behavior of the <a> tag's onclick and href properties is 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)

Fitment answered 14/2, 2013 at 4:1 Comment(5)
Is there also a way to do this with an element.addEventListener function?Pandich
Doesn't work for me, until I put href="#" there instead of a real URL.Tense
I'm using laravel framework, so in my blade view I included this, It is not working, have anyone tried this with laravel?Gradygrae
This solution is not working if i have any action method called in mvc controller in href. Can somebody please help ?Lempira
Does it make sense to first have onclick and then href? Probably to have a counter, popup etc with onclick and then going to the link?Ass
M
12

Use jQuery. You need to capture the click event and then go on to the website.

$("#myHref").on('click', function() {
  alert("inside onclick");
  window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myHref">Click me</a>
Mikemikel answered 14/2, 2013 at 4:1 Comment(2)
i won't use any javascript framework. but thank you for your answerBarkeeper
Above is not an actual link. It cannot be opened in a new tab and is a very bad practice. If something can be opened in a new tab (has na url) always add a meaningful href attribute.Perambulate
C
8

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

Campbellite answered 1/7, 2018 at 20:1 Comment(2)
This works for me in Chrome however Safari seems to run the function but not open the href...any sugestions?Bornholm
@Bornholm I made test on fiddle without JS - only pure html: <a href="http://example.com" >Item</a> and in Chrome i see some message to allow page to run this link (alert at the end of chrome url bar). In safari in console I see warrning: [blocked] The page at fiddle.jshell.net/_display was not allowed to display insecure content from example.com - so probably this is some security issue (only on fiddle ? )Plant
N
6

No jQuery needed.

Some people say using onclick is bad practice...

This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>
Nygaard answered 19/3, 2020 at 16:52 Comment(1)
This works by overriding the default behaviour, and there's nothing to say it's a bad practice. This is the approach I used as it removes the onClick (having href and onClick was confusing tbh), so thanks for this.Galbraith
A
2

Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.

We can style a button to look like an anchor element.

From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#onclick_events

Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

Anthropophagite answered 12/9, 2022 at 5:58 Comment(0)
C
0

Accepted answer didn't work for me. However, preventing the default behavior of a href and then 'manually' following the link, did work.

The code sample would be:

<a href="https://example.com" onClick="myFunction(event)">Link</a>
<script>
function myFunction(event) {
    event.preventDefault();
    // do your thing here
    window.location.href = event.currentTarget.href;
}
</script>
Chartres answered 1/3, 2023 at 8:55 Comment(0)
P
-5

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>
Providenciaprovident answered 21/10, 2018 at 1:24 Comment(1)
Only in AngularJSMichalmichalak

© 2022 - 2025 — McMap. All rights reserved.