Having trouble getting the following code to work. Calling swapLevel() directly works fine, but the addEventListener() doesn’t seem to be doing anything?
JavaScript:
<script>
function load() {
var arr = document.getElementById('menu').getElementsByClassName('level');
for (var i=0; i<arr.length; i++) {
arr[i].addEventListener('click', function(){swapLevel(i);}, false);
}
// automatically open the first level
swapLevel(0);
}
document.addEventListener('DOMContentLoaded', load, false);
</script>
HTML:
<div id="menu">
<a href="#" class="level">Level One</a>
<span class="hidden" id="0">
<p>Some options here</p>
</span>
<a href="#" class="level">Level Two</a>
<span class="hidden" id="1">
<p>More options</p>
</span>
<a href="#" class="level">Level Three</a>
<span class="hidden" id="2">
<p>Even more options</p>
</span>
</div>
You index is not what you think it is because the
forloop has run to completion before the event handler is called soiisarr.lengthin all your event handlers. Instead, you need something like this to capture the index value in a closure so it is what you want it to be in each event handler. A function call creates a closure so this example uses a self-execution anonymous function to create the closure: