0
<div id="w01">
<img src=qa/01.jpg alt='img'>
<img src=qa/02.jpg alt='img'>
<img src=qa/03.jpg alt='img'>
<img src=qa/04.jpg alt='img'>
</div>

CSS:

#w01 > img{
    display:none;
    width:100%;
}
#w01 > img:first-child{
    display:block;
}

This is starting position. All images are hidden except the first one.
Now I want to create an image gallery using jQuery array.
Click on Next button should move the first image at the bottom of stack, and display the next one.

var arr = $("#w01 > img").toArray();

$('.next').click(function(){
    var first = arr[0];
    arr.shift(first);
    arr[1].show(); //error
});

Error: Uncaught TypeError: undefined is not a function

Is something wrong in the concept, or just in the code, or both?

2
  • your code is included inside $(document).ready()? Commented May 11, 2014 at 10:40
  • @AlessandroMinoccheri, yes it is. alert (arr); gives me img objects Commented May 11, 2014 at 10:43

1 Answer 1

1
var arr = $("#w01 > img").toArray();

$('.next').click(function(){
    var first = arr[0];
    arr.shift(first);
    arr[1].show(); //error
});

Change to:

var arr = $("#w01 > img").toArray();

$('.next').click(function(){
    // var first = arr[0];
    // arr.shift(first);
    // $(arr[1]).show(); // This will not show any error. But it will not work as you expected.
    // See A. Wolff's comment for more details.

    // New
    $(arr[0]).hide(); // Hide showing img
    arr.push(arr.shift()); // Shift array
    $(arr[0]).show(); // Show new first img
});

Because arr[1] returns a pure Javascript DOM, while .show is a method of jQuery.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess it should be: $(arr[0]).show(); and BTW should use: arr.push(arr.shift(first));, shift() removing first item from array
Reegan, why image switching is stopped when reached the last image? It should display the first image again, in an endless circle !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.