5

I am aware that in-line scripting should be avoided by keeping html/css and javascript separated.

How is it possible to do such a thing in the following code? //consider above in the code the function alertMe() declared

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

How would it be possible not using in line code?

Thanks in advance.

5 Answers 5

9

With addEventListener():

var img = document.getElementById('littlebrain');
img.addEventListener('click', function(event){
  alertMe();
});
Sign up to request clarification or add additional context in comments.

Comments

2

In a JavaScript code file, you can find the img element by its id, and then you can set its onclick handler. For example, using jQuery:

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

In your case, the handler is a named function, called alertMe:

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

2 Comments

alertMe is already a function, so this can be shortened to $("#littlebrain").click(alertMe);
@DavidHammond Thanks David, I refined my answer.
2

It depends on the browsers you have to support, but if you're lucky and only get to 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 not so lucky, then 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 a library like jQuery, you can easily normalize the whole process

$('#thing').on('click', function() {
  // do something...
});

Comments

2
document.getElementById('littlebrain').onclick = function() { alertMe(); }

or even shorter:

document.getElementById('littlebrain').onclick = alertMe;

Comments

1
var el = document.getElementById('littlebrain');
el.addEventListener('click', alertMe, false);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.