Last active
December 22, 2017 00:55
-
-
Save ahmednooor/f69837e7af86c13c7082a9cdc71fde76 to your computer and use it in GitHub Desktop.
Helper function to attach events to each element in an array without using for loop.
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
// -- Function -- | |
function addEventToEach(arrayName, eventType, eventCallback) { | |
var i; | |
for (i = 0; i < arrayName.length; i += 1) { | |
arrayName[i].addEventListener(eventType, eventCallback, false); | |
} | |
return; | |
} | |
// -- Usage -- | |
/* - HTML: | |
<input class="btn-a" type="button" value="Button A1"> | |
<input class="btn-a" type="button" value="Button A2"> | |
<input class="btn-a" type="button" value="Button A3"> | |
<input class="btn-b" type="button" value="Button B1"> | |
<input class="btn-b" type="button" value="Button B2"> | |
<input class="btn-b" type="button" value="Button B3"> | |
*/ | |
// - Javascript: | |
var buttonsA = document.getElementsByClassName("btn-a"), | |
buttonsB = document.getElementsByClassName("btn-b"); | |
function doSomethingA() { | |
// do something when event on buttonsA[i] gets fired ... | |
} | |
function doSomethingB() { | |
// do something when event on buttonsB[i] gets fired ... | |
} | |
function addEventToEach(arrayName, eventType, eventCallback) { | |
var i; | |
for (i = 0; i < arrayName.length; i += 1) { | |
arrayName[i].addEventListener(eventType, eventCallback, false); | |
} | |
return; | |
} | |
addEventToEach(buttonsA, "click", doSomethingA); | |
addEventToEach(buttonsB, "click", doSomethingB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment