Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook into an onClick event without using the HTML property

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" />
like image 969
Mark Tomlin Avatar asked May 27 '11 20:05

Mark Tomlin


1 Answers

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 */
});
like image 147
Jesufer Vn Avatar answered Oct 20 '22 16:10

Jesufer Vn