HTML tag <a> want to add both href and onclick working

user1589113 picture user1589113 · Feb 14, 2013 · Viewed 515.8k times · Source

I'd like to ask about HTML tag

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

How to make this a tag working with href and onClick? (prefer onClick running first then href)

Answer

Ian picture Ian · Feb 14, 2013

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)