Skip to content Skip to sidebar Skip to footer

How To Change The Images On Button Click

I want to change the image by pressing the button.I have two button, one is next and other is previous.When the next button press new image must be shown and previous button press

Solution 1:

http://jsfiddle.net/S6t9R/4/

$(document).ready(function () {
    $('img:not(:first)').hide();
    $(".arrow").click(function () {
        $('img:not(:last):visible').
        hide().
        parent().
        next().
        children().
        show();
    });
    $(".leftarrow").click(function () {
        $('img:not(:first):visible').
        hide().
        parent().
        prev().
        children().
        show();
    });
});

basically, the image that is visible is now hidden, and the next/previous image is now visible.

Solution 2:

Maybe in this case you could hide/show the div-elements around your images. If you hide an image the way you do, the div itself will still be 'visible' in the document, which is probably what gives you the unwanted result.

Solution 3:

Change your script,

 $(document).ready(function () {
  $('#secondimage').hide();
  $('#thirdimage').hide();
 $(".arrow").click(function () {
    $('#firstimage').hide();
    $('#secondimage').show();
  });
$(".leftarrow").click(function () {
    $('#firstimage').show();
    $('#secondimage').hide();
  });
});

Solution 4:

How about changing the image src?

JavaScript:

var images = [
    "alpha.jpg",
    "beta.jpg",
    "gamma.jpg"
];
var actImg = 0; // index of actual image

$(document).ready(function () {
    $(".leftarrow").click(function () {
        if (actImg <= 0) { // if first image is displayed, jump to last
            actImg = images.length - 1;
        }
        else {
            actImg--;
        }
        $('#onlyimage').attr('src', images[actImg]);
    });
    $(".rightarrow").click(function () {
        if (images.length <= actImg) { // if last image is displayed, jump to first
            actImg = 0;
        }
        else {
            actImg++;
        }
        $('#onlyimage').attr('src', images[actImg]);
    });
});

HTML:

<divclass="imageDiv"><div><imgsrc="alpha.jpg"class="image"id="onlyimage"/></div><div><inputtype="image"src="leftarrow.gif"class="leftarrow"/></div><div><inputtype="image"src="rightarrow.gif"class="rightarrow"/></div></div>

Solution 5:

$(document).ready(function () {
    that = this;
    this.arrayImages = $('.image');
    this.currentPosition = 0;
    $('#secondimage').hide();
    $('#thirdimage').hide();
    $(".arrow").click(function () {
        if (that.currentPosition < that.arrayImages.length) {
            that.arrayImages[that.currentPosition].hide();
            that.arrayImages[that.currentPosition+1].show();
            that.currentPosition++;
        }
    });
});

For the leftarrow it's just the other way (:

Post a Comment for "How To Change The Images On Button Click"