Inclusion in onClick event without using HTML property

I would like to leave 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 connect to the onClick event, for example, above, but without using the onClick property of the HTML in it. In addition, I would like to keep it agnostic using raw JavaScript, not frameworks like jQuery or MooTools (although if you want to present them as illustrations along with raw JavaScript, that would be nice too).

 <input type="text" name="text" /> 
+7
javascript html
source share
3 answers

To work with JavaScript, first, you need to add an identifier to the element that you want to add to the event. This is because it simplifies the understanding of your code and avoids confusion when writing code. So the HTML line will look like this:

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

For each element that is unique throughout the document, there should be no more than one identifier. 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 latter is that you can add as many click events (or mouseover, ...) as you want, and deleting them one by one is possible. But it does not work with IE <9. Instead, you should use:

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

jQuery:

 $("#myInputType1").click(function(){ /*Your code goes here */ }); 
+13
source share

By assigning an identifier to your input element, you can easily (and efficiently) access it using 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 a warning in the onclick function ...

+4
source share

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

 var el = document.getElementById("text"); el.addEventListener("click", function(/*put code here*/) {}, false); 
+1
source share

All Articles