Shensheng Wang
Shensheng Wang

Reputation: 21

passing arguments to an onchange() function

I'm trying to create an image slider, in which moving the handle on the slider will change the image to be displayed.

In the code below, I use an onchange function to dynamically update the image (id = "image") based on the current value of slider (id = "image-slider-response").

     var imageGroup1 = ['imageA.jpg','imageB.jpg','imageC.jpg'];
     var slide = document.getElementById('image-slider-response');
     var imageDiv = document.getElementById("image");
     slide.onchange = function() {
         imageDiv.src = imageGroup1[this.value];
     }

Now, I'm trying to pass imageGroup as an argument to the onchange function to extend the code above to other image groups. I followed this link http://www.jstips.co/en/javascript/passing-arguments-to-callback-functions/ but didn't seem to work. Any suggestions to fix this?

    var imageGroup1 = ['imageA.jpg','imageB.jpg','imageC.jpg'];
    var imageGroup2 = ['imageD.jpg','imageE.jpg','imageF.jpg'];
    var slide = document.getElementById('image-slider-response');
    var imageDiv = document.getElementById("image");

    function myFunction(x){
        return function(){
            sliderDiv.innerHTML = slide.value;
            imageDiv.src = x[slide.value];
        }
    }
    var imageGroup = imageGroup1;
    slide.addEventListener("onchange", myFunction(imageGroup));

Upvotes: 0

Views: 34

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

You're on the right track with the callback there, there's just one thing - when using addEventListener, don't prefix the event with on: just use the plain event name.

slide.addEventListener("change", myFunction(imageGroup));

Upvotes: 1

Related Questions