How to change behavior of <a href=“somewhere.html” id=“link”> with jQuery?

StackOverflow https://stackoverflow.com/questions/1442226

  •  22-07-2019
  •  | 
  •  

Question

For those with javascript enabled,click on them should do OnClick()

For those with javascript disabled,click on them should just go to somewhere.html,

Suppose only $('#link') is accessible,how to do that?

Was it helpful?

Solution

Like this:

$('#link').click(function() { 
    //...
    return false;
});

By writing return false, the link will not be followed.

If Javascript is disabled, the click handler won't be added, and the link will behave normally.

OTHER TIPS

$("#link").bind("click", function(e){alert("clicked"); e.preventDefault(); return false;});

This will alert "clicked" and then cancel the default action. If Javascript is disabled, the link is followed.

Use the click function. Add return false to the end of your function to prevent the default action of the click, which is following the hyperlink:

$("#link").click(function() { onClick(); return false; });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top