-1

I have a JavaScript function showImage that shows an image with a particular ID. I have an HTML link that calls that function

<a href="javascript:showImage('img1')">show image1</a>

Is it a good idea to call a JavaScript within HTML a tag like this? It seems to work, but is this the "correct" way to do it?

Mika H.
  • 4,119
  • 11
  • 44
  • 60
  • I'm not sure of what your question exactly is but maybe [this answers](http://stackoverflow.com/questions/138884/when-should-i-use-inline-vs-external-javascript). – Denys Séguret Mar 16 '13 at 18:02
  • If you have a library such as jQuery it is as easy giving your image an ID and attaching a click handler, but if you're using pure JS and want cross-browser compatibility, yours is fine. – Fabrício Matté Mar 16 '13 at 18:05
  • Of course the above is just my opinion. If you were to make it unobtrusive with pure JS it'd take feature testing for `attachEvent('onclick', fn)` vs `addEventListener('click', fn)` just to have the same outcome which you already have. – Fabrício Matté Mar 16 '13 at 18:07
  • Thanks, Fabricio! Since I have many images, I want to use a class instead. Can JQuery attach a click handler to everything in a certain class? – Mika H. Mar 16 '13 at 18:08
  • Yeah of course. Here's an example using `data-` attributes so you can use the same handler for all links. http://jsfiddle.net/ult_combo/qsR2Y/ or with a class selector http://jsfiddle.net/qsR2Y/1/ – Fabrício Matté Mar 16 '13 at 18:18

2 Answers2

2

Most of the time you don't want to couple your HTML with your javascript code. It's better to attach an event handler that is transparent to the user. This way if a user has javascript disabled you can gracefully degrade.

Many ways to solve the problem, it all depends on what approach is required.

See also:

ryan
  • 6,541
  • 5
  • 43
  • 68
1

It seems to work, but is this the "correct" way to do it?

Correct is extremely subjective, but probably not.

You should investigate unobtrusive JavaScript.

Try using something like this:

document.getElementById('my_link').addEventListener('click', function (event) {
    event.preventDefault();
    showImage('img1');
}, false);
pdoherty926
  • 9,895
  • 4
  • 37
  • 68