Alternative to built-in scripts in JavaScript

I know that in-line scripting should be avoided while maintaining the separation of html / css and javascript.

How can this be done in the following code? // consider the function alertMe()declared above in the code

<img src="LittleBrain.png"  id="littlebrain" onClick="alertMe();">

How could one not use string code?

Thanks in advance.

+4
source share
5 answers

C addEventListener():

var img = document.getElementById('littlebrain');
img.addEventListener('click', function(event){
  alertMe();
});
+9
source
document.getElementById('littlebrain').onclick = function() { alertMe(); }

or even shorter:

document.getElementById('littlebrain').onclick = alertMe;
+2
source

JavaScript img id, onclick. , jQuery:

$("#littlebrain").click(function () {
  // ...handler code here...
});

, alertMe:

$("#littlebrain").click(alertMe);
+2

It depends on the browsers you have to support, but if you are lucky and only worry about modern browsers, you can use .addEventListener()

var thing = document.getElementById('thing');

thing.addEventListener('click', function(e) {
  // do something here!
}, false);

If you're out of luck, you'll have to come up with a cross browser solution.

var thing = document.getElementById('thing');

addEvent(thing, 'click', function() {
  // do something
});

function addEvent(elem, event, callback) {
  if (elem.addEventListener) {
    elem.addEventListener(event, callback, false);
  } else if (elem.attachEvent) { // IE7 and earlier
    elem.attachEvent('on' + event, function() {
      callback.apply(elem, arguments);
    });
  } else {
    elem['on' + event] = callback;
  }
}

Or, if you use jQuery library, you can easily normalize the whole process

$('#thing').on('click', function() {
  // do something...
});
+2
source
var el = document.getElementById('littlebrain');
el.addEventListener('click', alertMe, false);
+1
source

All Articles