HTML anchor tag with Javascript onclick event

JavascriptHyperlinkOnclickAnchor

Javascript Problem Overview


On using Google I found that they are using onclick events in anchor tags.

In more option in google header part, it looks like normal a tag, but onclicking it doesn't get redirected but opened a menu. Normally when using

<a href='more.php' onclick='show_more_menu()'>More >>></a>

It usually goes to 'more.php' without firing show_more_menu(), but I have show a menu in that page itself. How to do like google?

Javascript Solutions


Solution 1 - Javascript

If your onclick function returns false the default browser behaviour is cancelled. As such:

<a href='http://www.google.com' onclick='return check()'>check</a>

<script type='text/javascript'>

function check()
{
	return false;
}

</script>

Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

Solution 2 - Javascript

You can even try below option:

<a href="javascript:show_more_menu();">More >>></a>

Solution 3 - Javascript

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>

Solution 4 - Javascript

Use following code to show menu instead go to href addres

function show_more_menu(e) {
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();
}

<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsmartkidView Question on Stackoverflow
Solution 1 - JavascriptTJHeuvelView Answer on Stackoverflow
Solution 2 - Javascriptsun2View Answer on Stackoverflow
Solution 3 - JavascriptAditya ManoharView Answer on Stackoverflow
Solution 4 - JavascriptKamil KiełczewskiView Answer on Stackoverflow