Created
September 2, 2011 15:24
-
-
Save walterg2/1188909 to your computer and use it in GitHub Desktop.
Quick Example of a good use of JavaScript's apply function
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> | |
</head> | |
<body> | |
<h1>Apply Test</h1> | |
<p>Click the Next and Back buttons or use your arrow keys to see your counter go up and down.</p> | |
<div id="counter"></div> | |
<form action="#"> | |
<input type="button" name="next" value="Next" id="next" /> | |
<input type="button" name="previous" value="Back" id="previous" /> | |
</form> | |
<script> | |
(function () { | |
var count = 0, | |
nextButton = document.getElementById("next"), | |
previousButton = document.getElementById("previous"), | |
counter = document.getElementById("counter"); | |
increment = function (direction) { | |
if (direction === "Up") { | |
count = count + 1; | |
} else { | |
count = count - 1; | |
} | |
return count; | |
}, | |
action = function () { | |
var link = this; | |
if (link.id === "next") { | |
counter.innerHTML = increment("Up"); | |
} else { | |
counter.innerHTML = increment("Down"); | |
} | |
return false; | |
}, | |
keyPress = function (e) { | |
if (e.keyCode === 37 || e.keyCode === 40) { | |
action.apply(previousButton); | |
} else if (e.keyCode === 38 || e.keyCode === 39) { | |
action.apply(nextButton); | |
} | |
}, | |
addEvent = function (obj, type, fn) { | |
if (obj.addEventListener) { | |
obj.addEventListener(type,fn,false); | |
return true; | |
} else if (obj.attachEvent) { | |
obj['e'+type+fn] = fn; | |
obj[type+fn] = function() { obj['e'+type+fn]( window.event );} | |
var r = obj.attachEvent('on'+type, obj[type+fn]); | |
return r; | |
} else { | |
obj['on'+type] = fn; | |
return true; | |
} | |
} | |
; | |
counter.innerHTML = count; | |
addEvent(previousButton, 'click', action); | |
addEvent(nextButton, 'click', action); | |
addEvent(document, 'keydown', keyPress); | |
}()); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment