jqueryhtmlcssbackground-position

change position of one background image in a multi backgrounded div


I have a simple HTML : <div id="wrapper"></div> and this style sheet:

#wrapper{

        position: absolute;

        width: 400px;
        height: 400px;     

        background-image: url(img1.png), url(img2.png);

        background-repeat: no-repeat, no-repeat;

        background-position: top center, center center;

        background-color: green;
        border: 1px solid black;

}  

as above style sheet shows #wrapper has two background images in different positions. I want to change second image position on mouse click with applying no change on the first image position. what syntax do i have to use?

my jquery code :

$("#wrapper").click(function(){
    this.css("background-position": " ? , bottom right " );
});

i think ? should be replaced with something like !important but !important does not works for applying no change on first image.

position of both background images will change in different places, and i dont know what is the first image position now, i can save its position in a variable, but i rather to use native solution, if exists
any suggestion?


Solution

  • change background position 2

    This will replace the second background position (after comma) with bottom right:

    $('#wrapper').click(function() {
        $(this).css('background-position', function() {
            return this.style.backgroundPosition.replace(/,(.*)$/, ', bottom right');
        });
    });
    

    change background position 1

    And this will replace the first background position (before comma) with bottom right:

    $('#wrapper').click(function() {
        $(this).css('background-position', function() {
            return this.style.backgroundPosition.replace(/(.*),/, 'bottom right, ');
        });
    });
    

    this solution is a good choice if element has only two backgrounds and we want to change position or any other property of each background images