Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing JavaScript when a link is clicked

Tags:

javascript

Which is preferable, assuming we don't care about people who don't have JavaScript enabled?

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

Or

<a href="javascript:executeSomething()"></a>

Is there any difference?

Or there any other ways I'm missing besides attaching an event to the anchor element with a JavaScript library?

like image 819
JamesBrownIsDead Avatar asked Nov 20 '09 03:11

JamesBrownIsDead


2 Answers

The nice thing about onclick is you can have the link gracefully handle browsers with javascript disabled.

For example, the photo link below will work whether or not javascript is enabled in the browser:

<a href="http://www.example.com/myPhoto.jpg" target="_blank" onclick="showPhoto(this.href); return false;">foobar</a>
like image 151
Rob Avatar answered Sep 28 '22 23:09

Rob


it's better to use the onclick because that's the way the things should be.

The javascript: was somekind of hackish way to simulate the onclick.

Also I advice you to do some non intrusive Javascript as much as possible, it make the code more easy to read and more maintainable!

like image 27
RageZ Avatar answered Sep 28 '22 23:09

RageZ