views:

174

answers:

1

Hey,

I pretty new to js and jquery so please bear with me.

I'd like to change the background-position and add 1% on #div1 while clicking on #button1 and take -1% on #div1 while clicking on #button2

How could i achive this in jQuery?

Alse, bonus question: These are going to get dynamically generated through php. Is it possible to use php in the js-script so the id's get correct?

like this:

$i = 1
while($i <= 5):
 $div[$i] = 'div'.$i;
 $leftbutton[$i] = 'leftbotton'.$i;
 $rightbotton[$i] = 'rightbotton'.$i;
$i++;
endwhile;

Else i'll have to learn how to make loops in js as well ;)

Edit: Follow up questions:

How can i update a text field with this value as i click the buttons? And how do i modify it if i'd like to add up/down buttons as well? thanks a bunch!

Thanks in advance! -Simon

+2  A: 

Like this:

function makeClicker(index) {
    $('#leftbutton' + index).click(function() {
        var bPos = $('#div' + index).css('background-position');
        bPos = bPos.replace(/%/g, '').split(' ');
        bPos = (-1 + parseInt(bPos[0], 0)) + '% ' + bPos[1] + '%';
        $('#div' + index).css('background-position', bPos);
    });
    $('#rightbutton' + index).click(function() {
        var bPos = $('#div' + index).css('background-position');
        bPos = bPos.replace(/%/g, '').split(' ');
        bPos = (1 + parseInt(bPos[0], 0)) + '% ' + bPos[1] + '%';
        $('#div' + index).css('background-position', bPos);
    });
}

for(var i = 1; i <= 5; i++)
    makeClicker(i);

EDIT: Fixed mistakes.

Demo

SLaks
I don't know. Will that take the current value and add or decrease (well obviously not in percent, like i asked, but in pixels) it?
cinnak
I tested it, and it won't. Wait while I edit.
SLaks
Thanks! Couldn't get it to work though. Here is the code of the element i want to change the style on:<a id="div<?php echo $p; ?>" href="<?php echo $linky[$p]; ?>" style="display:block;width:180px;height:488px;background:#CCC url(<?php echo wp_get_post_image('height=488 ?>) <?php echo $position[$p]; ?> 0%;">Since the image is dynamically fetched it needs to be inline-styled.
cinnak
Saw the update, it works now, thanks!
cinnak
Follow up questions (if you've got time): How can i update a text field with this value as i click the buttons? And how do i modify it if i'd like to add up/down buttons as well? thanks a bunch!
cinnak
Re #1: `$('.myDivElement').text('Position: ' + bPos);`. Re #2: `bPos[0]` is X, and `bPos[1]` is Y. You'd need to move the `(1 +parseInt(` to `bPos[1]`.
SLaks
Thanks again, everything works now! Though i had to use <pre>$('.myDivElement' + index).attr("value", bPos);</pre> in #1
cinnak