-1

How can I do to change background image onClick with jquery or java script?

For Example: I have Six(6) images and I want change to NEXT background image when i click on ">" (next arrow) and change to previous background image when I click on "<" (back arrow).

I'm developing this website with responsive html5 and css3.

user1777158
  • 9
  • 2
  • 4
  • why dont you use image jquery slide show.have look at this. [21 Best jQuery Image Gallery](http://www.rswebsols.com/tutorials/jquery/21-best-jquery-image-gallery-photo-slideshow) – Milind Anantwar Oct 26 '12 at 13:21
  • 2
    http://stackoverflow.com/questions/10867503/change-background-image-in-body – jonvuri Oct 26 '12 at 13:22

3 Answers3

2

You can list your images in an array and then change the background-image css attribute on click:

var images = ['url("image1.png")', ...], curIndex = 0;

// Left arrow selector
$('.left-arrow').click(function () {
    if (curIndex > 0) {
        // Container selector
        $('#container').css('background-image', images[--curIndex]);
    }
});

// Right arrow selector
$('.right-arrow').click(function () {
    if (curIndex < images.length - 1) {
        // Container selector
        $('#container').css('background-image', images[++curIndex]);
    }
});

HTML Would be:

<div id="container">
    <img class="left-arrow" src="image-path" />
    <img class="right-arrow" src="image-path" />
<div>
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • Could you give me an exampe with the css and html file? Thankx in advance – user1777158 Oct 26 '12 at 16:48
  • @user1777158 I have changed the example to show what the HTML would look like. Of course you can change the elements and their relationships with each-other. Also there is no css, I use the class to select by but you can also define styles for those. – Konstantin Dinev Oct 26 '12 at 21:44
1

If you don't want to use any other 3rd party libraries:

$("#YourElementId").css("background-image", "url('http://url.com/image1.jpg')");
Mario S
  • 11,715
  • 24
  • 39
  • 47
0
$("#id").on("click", function () {
    $(this).css("background-image", "url(/url/to/background/image.jpg)");
});
chridam
  • 100,957
  • 23
  • 236
  • 235