Kristian Daugaard
Kristian Daugaard

Reputation: 185

Parameter for addEventListener doesn't seem to work properly

I am creating a "slideshow" if you will call it that, for page navigation.

I am attempting to use a forloop to add an eventlistener to all menu items. And it doesn't seem to work. Basically i have a function that shows a new page, based on a parameter.

function slidePFer(page_side){

And this works perfectly by setting the eventlisteners manually like this:

showPF  = document.getElementsByClassName('showPF');

showPF[0].addEventListener('click', function(){ slidePFer(0); }, false);
showPF[1].addEventListener('click', function(){ slidePFer(1); }, false);
showPF[2].addEventListener('click', function(){ slidePFer(2); }, false);
showPF[3].addEventListener('click', function(){ slidePFer(3); }, false);

This looks however very messy. So i attempted to run though it all with different loops. And i just can't make it work, here is one of the more promissing loops i have tried:

for(var i=0, n=showPF.length; i<n; i++){
    showPF[i].addEventListener('click', function(){ slidePFer(i); }, false);
}

Can anybody see what i appear to not understand?

Upvotes: 0

Views: 120

Answers (3)

Kristian Daugaard
Kristian Daugaard

Reputation: 185

I finally found the solution myself for anyone interested this is how i did it:

showPF          = document.getElementsByClassName('showPF');

var i = showPF.length;
    while(i--){
        showPF[i].addEventListener('click', function(x){ return function(){ slidePFer(x); }; }(i),false);
    }

Credit where credit does: http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside-a

Upvotes: 0

Latheesan
Latheesan

Reputation: 24116

With jQuery (http://jquery.com), you can simplify this like this:

html

<img slideNo="0" class="showPF" src="slide_0_preview.jpg" />
<img slideNo="1" class="showPF" src="slide_1_preview.jpg" />
<img slideNo="2" class="showPF" src="slide_2_preview.jpg" />

javascript

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('.showPF').click(function() {
            slidePFer($(this).attr('slideNo'));
        });
    });
    function slidePFer(slideNo) {
        // todo
    }
</script>

Upvotes: 0

Azzy Elvul
Azzy Elvul

Reputation: 1438

Remove i from function(i) Maybe this will fix it

Upvotes: 1

Related Questions