Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page jumps to the top onclick [duplicate]

Tags:

javascript

I have a click in the middle of a website with code like <a href=“#“ onclick=“…

The function works well, but the a href=“#“ let’s the page always jump to the top when I click on the link. Is there any way around it?

Thanks

like image 497
Denise Avatar asked Nov 29 '22 03:11

Denise


2 Answers

Just add ; return false; to the end of your onclick, for example:

<a href="#" onclick="alert('hello'); return false;">

Edit: Hemlock's answer is a good alternative, but yet another one is a combination of the two:

<a href="javascript:void(0)" onclick="alert('hello')">

The advantage of this is that you're explicitly saying that the <a> should do nothing with the href, and the onclick event handler is a separate attribute. If you later decide to attach the onclick handler using JavaScript rather than inlining it (recommended), it's simply a matter of removing the onclick attribute.

like image 125
David Tang Avatar answered Dec 07 '22 23:12

David Tang


Alternate method

<a href="javascript: alert('hello'); void(0);"></a>

Put the javascript in the href and make sure the code ends in a call to void

like image 42
Hemlock Avatar answered Dec 07 '22 23:12

Hemlock