Creating a list of Anchor tags

I am creating a list of anchor tags from a MySQL / PHP query; anchor tags call a JavaScript function.

"Trick 22" I have:

  • href = "#" causes the page to jump to the top with every click of one of the anchor tags (very annoying).
  • deleting href = "#" means that the cursor does not change when the anchor tag is hovering over, and this anchor tag does not have an anchor tag.

I know there is a way to handle this using JavaScript (maybe jQuery), but I donโ€™t remember how it is at the moment. However, I really prefer a simplified HTML fix (if one exists) that does not require me to access JavaScript.

Edit: "does not require me to get into JavaScript" == "does not require significant changes to JavaScript."

+6
source share
5 answers

A simpler HTML fix for you: Personally, for simple test links I just use href=""

For links pointing to a javascript function, I use href="javascript:;" . In any case, you will stop page skipping.

+2
source

In your javascript function, you must return false , or using jquery you can use preventDefault()

Example:

 $('a').click(function(event) { event.preventDefault(); // do something }); 

Or in your case:

 <a href="#" onclick="foo();return false;"> 

Or change href to javascript:void(0) :

 <a href="javascript:void(0)" onclick="foo();"> 

Ideally, your link gets worse without javascript, so you can usually avoid the third option.

+4
source

return false after onclick or from the foo () function.

+1
source

You need to call event.preventDefault(); somewhere in the click event handler. In vanilla javascript, this can be done like this:

 <script type="text/javascript"> function foo(e) { e.preventDefault(); // other code } </script> <a href="#" onclick="foo(e);"></a> 

Alternatively, you can also return false:

 <a href="#" onclick="foo();return false;/> 

This can also be done in jQuery quite simply:

 $('.mylink').click(function(e) { e.preventDefault(); // other code }); 

The downside of using return false; is that it also prevents the event from flowing into the DOM. If you don't care about event bubbles, it's ok to use a lie, but personally, I feel it is better to use event.preventDefault(); unless you specifically want to stop the event bubbles.

+1
source
 <html> <head> </head> <body> <style> a { text-decoration: underline; } a:hover { text-decoration: underline; } </style> <script type="text/javascript"> function foo() { alert('Hello World'); } </script> <a onclick="foo();">Click Here</a> </body> </html> 

Just adding CSS and removing href seems fine.

0
source

Source: https://habr.com/ru/post/891463/


All Articles