164

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?

Chris
  • 1,206
  • 2
  • 15
  • 35
  • Check this **[Set A tag link in HTML using JavaScript](https://debug.to/3093/how-to-replace-string-in-current-url-with-javascript)** – Mohamed Dec 24 '21 at 14:35
  • This one may help, It works for me : https://stackoverflow.com/a/7347854/14437411 – Menaim Feb 01 '22 at 22:19

7 Answers7

285

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)

Ian
  • 50,146
  • 13
  • 101
  • 111
11

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>
Franklin Yu
  • 8,920
  • 6
  • 43
  • 57
Sudipta Chatterjee
  • 4,592
  • 1
  • 27
  • 30
  • 13
    i won't use any javascript framework. but thank you for your answer –  Feb 14 '13 at 04:34
  • 9
    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. – Nux Aug 23 '16 at 10:44
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.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • This works for me in Chrome however Safari seems to run the function but not open the href...any sugestions? – Ben Sep 30 '18 at 21:35
  • @Ben I made test on fiddle without JS - only pure html: `Item` 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 https://fiddle.jshell.net/_display/ was not allowed to display insecure content from http://example.com/ - so probably this is some security issue (only on fiddle ? ) – Kamil Kiełczewski Oct 07 '18 at 16:46
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>
TeamDman
  • 649
  • 6
  • 26
  • 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. – Ron Holmes Feb 09 '23 at 03:38
1

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.

Arun
  • 205
  • 2
  • 4
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>
Viktor Brešan
  • 5,293
  • 5
  • 33
  • 36
-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>
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
mak-273
  • 62
  • 1
  • 7