Created
January 19, 2016 17:06
-
-
Save bzdgn/cf2a118ce674a0946cd7 to your computer and use it in GitHub Desktop.
Dom Event Listener Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<style> | |
#myDiv { | |
background-color: coral; | |
border: 1px solid; | |
padding: 50px; | |
color: white; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Dom Event Listener Example #06</h1> | |
<br> | |
<div id="myDiv"> | |
<p><strong>Click toggle button to switch event on/off</strong></p> | |
<button type="button" id="eventToggle">Toggle Event</button><br> | |
</div> | |
<p id='output'>Output: </p> | |
<script> | |
"use strict"; | |
var outPre = document.getElementById("output").innerHTML; | |
var output = document.getElementById("output"); | |
var myDiv = document.getElementById("myDiv"); | |
var myButt = document.getElementById("eventToggle"); | |
var isEventAdded = false; | |
prepare(); | |
function prepare() { | |
addEventToDiv(); | |
myButt.addEventListener ("click", handleButton ); | |
} | |
function handleButton() { | |
if( isEventAdded == false ) { | |
addEventToDiv(); | |
} else { | |
removeEventFromDiv(); | |
} | |
} | |
function updateOutput() { | |
output.innerHTML = Math.random(); | |
} | |
function addEventToDiv() { | |
addEvent(myDiv, "mousemove", updateOutput); | |
isEventAdded = true; | |
} | |
function removeEventFromDiv() { | |
removeEvent(myDiv, "mousemove", updateOutput); | |
isEventAdded = false; | |
} | |
function addEvent(el, event, func) { | |
el.addEventListener(event, func); | |
} | |
function removeEvent(el, event, func) { | |
el.removeEventListener(event, func); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment