user2662335
user2662335

Reputation: 19

How can i change the position of an image in Jquery?

I have an image like this:

enter image description here

and i want to change the position in jquery on hover to make it look the the image is changing.

I dont want to use the .animate function to shift the image but, to basically have the image scroll to each frame.

right now i have a width set, and my overflow to hidden so you can only see one image at a time.

my HTML

 <ul class="icons">
                    <li id="trasklogo"><img src="img/icons/nav-se1aec3ccea.png" width="75" height="823" /></li>
                    <li><img src="img/icons/sprite_about.png" width="1050" height="70" /></li>
                    <li><img src="img/icons/sprite_genetics.png" width="1050" height="70" /></li>
                    <li><img src="img/icons/sprite_innovation.png" width="1050" height="70" /></li>
                    <li><img src="img/icons/sprite_media.png" width="1050" height="70" /></li>
                </ul>

my CSS

ul li, {
list-style: none;
}

li {
display: list-item;
text-align: -webkit-match-parent;
}
.menu .icons #trasklogo {
height: 87px;
overflow: hidden;
}
.container .menu .icons {
width: 75px;
overflow: hidden;
}

Upvotes: 1

Views: 3618

Answers (2)

Appleshell
Appleshell

Reputation: 7388

You can easily create that effect in Javascript with JQuery.

setInterval(function() {
    // parse the current margin to an integer and substract the with of one frame
    var nr=parseInt($("#sw").css("margin-left")) - 70; 
    // reset margin to 0 if margin > last frame
    if(nr<=-1050) {
        nr=0;
    }
    // set the new margin
    $("#sw").css("margin-left", nr+"px");
}, 50);

CSS:

#wr {
    width:70px;
    overflow:hidden;
}

HTML:

<div id="wr">
    <img id="sw" src="https://i.sstatic.net/hCX5s.png" />
</div>

Working example: http://jsfiddle.net/U2MrB/

Upvotes: 1

Matthew R.
Matthew R.

Reputation: 4350

It's not entirely clear what you are trying to accomplish.

If you are trying to make this sprite an animation, take a look at Spritely. This javascript will automatically move the sprite to emulate keyframe animation. You simply supply a width and how quickly the sprite should move and it will do the rest.

If you are trying to slowly pan across the image and stop, your best bet would be to use animate on the background x position. I doubt this is your intention based on the sprite you've supplied and the fact that you requested not to use animate.

You could also emulate this animation with CSS using @keyframes. See this fiddle: http://jsfiddle.net/ZLyrN/

Note: CSS animations are not cross-browser compatible without a polyfill.

Upvotes: 1

Related Questions