<!-- Easy JavaScript # 30 - intro to Event Listeners -->
<p>
Welcome to the 30th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We've looked at event handlers, now lets look at Event Listeners!
</p>
<p>
There are many kinds of events that your browser can listen for. And the same target can event listener to a target multiple times (something event handlers cannot do). Some examples are:
</p>
<ul>
<li>Click/Double Click</li>
<li>Mouse Over/Out</li>
<li>Key Up/Down</li>
<li>Scroll/Resize (window object)</li>
<li>Focus</li>
<li>Blur</li>
<li>Load</li>
</ul>
<p>
See more events at MDN: <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener" target="_blank">https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener</a>
</p>
<h2>
Syntax of an Event Listener:</h2>
<p>
<code><pre>
element.addEventListener("event",function(){
//do something when the event takes place
});</pre>
</code>
</p>
<p>
Let's take a look!
</p>
<button id="name">Name</button>
<button id="city">City</button>
<p>
<input id="userAction" type="text" size="60"/>
<span id="keyPress"></span>
</p>
CSS
#outputName, #outputCity{
color: red;
}
JavaScript
document.getElementById("name").addEventListener("click",function(e){
alert("I have been clicked");
});
document.getElementById("name").addEventListener("click",function(){
var btnName = this.getAttribute('id');
document.getElementById("userAction").value = btnName + " has been clicked";
});
document.getElementById("city").addEventListener("click",function(){
var btnName = this.getAttribute('id');
document.getElementById("userAction").value = btnName + " has been clicked";
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.