7

I would like to keep my JavaScript and HTML code separate. To do this, I want to make sure that I never use the following syntax:

<input type="text" name="text" onClick="javascript:onClick(this)" />

But I want to hook into the onClick event for example the above input but without having to use the onClick property within it's HTML. Furthermore, I would like to keep it implementation agnostic, using raw JavaScript and not the frameworks like jQuery or MooTools (Although, if you wish to provide those as illustrations along with the raw JavaScript that would be good too).

<input type="text" name="text" />
Mark Tomlin
  • 8,593
  • 11
  • 57
  • 72

3 Answers3

16

To work with JavaScript, first, you have to add an id to the element that you want to append an event. That is because it makes it easy to understand your code and avoids confusion when you are writing your code. So, the HTML line will look like:

<input type="text" name="text" id="myInputType1" />

There must be no more than one id per element that is unique in the whole document. Now, there are three main ways to add events:

/* First */
document.getElementById("myInputType1").onclick = function(){
    /*Your code goes here */
};

/* Second */
function Func(){
    /*Your code goes here */
}
document.getElementById("myInputType1").onclick = Func;

/* Third */
function Func(){
    /*Your code goes here */
}
document.getElementById("myInputType1").addEventListener("click", Func, false);

The advantage of the last one is that you can append as many "click" (or "mouseover", ...) events as you like, and removing them one by one is possible too. But it does not work with IE<9. Instead, you have to use:

document.getElementById("myInputType1").attachEvent("onclick", Func);

jQuery way:

$("#myInputType1").click(function(){
    /*Your code goes here */
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Jesufer Vn
  • 13,200
  • 6
  • 20
  • 26
  • 1
    You should mention that [`addEventListener`](https://developer.mozilla.org/en/DOM/element.addEventListener) doesn't work for IE <9; instead, you have to use [`attachEvent`](http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx). – Kevin Ji May 27 '11 at 21:59
  • +1, and respect for the detail in the answer, thank you, I have a much better understanding of this now. – Mark Tomlin May 28 '11 at 20:32
5

By assigning an ID to your input element, you will easily (and efficiently) be able to access it with raw javascript

<input type="text" name="text" id="myInput" />

In your separate javascript :

var input = document.getElementById("myInput");

input.onclick = function() {alert("clicked");}

Obviously you would do something more useful than an alert in the onclick function...

Hugo Migneron
  • 4,867
  • 1
  • 32
  • 52
1

If you give your element and ID, you can do:

var el = document.getElementById("text");
el.addEventListener("click", function(/*put code here*/) {}, false);
Dave
  • 2,409
  • 3
  • 22
  • 28