I am using JQuery and would like to do the following. I have 2 images of a car. One that faces left and one that faces right (x-axis). When a user clicks and drags the car in a direction I want the image
of the car to switch to be the one that faces in the same direction.
Here’s what I have so far:
I have a DIV called #car that is assigned to this code
$(function() {
$( "#car" ).draggable();
});
and it drags just fine. I then have an image that is wrapped in the #car div called #myImage and the HTML code is as follows:
<img id="myImage" src="" alt="" height="42" width="42" />
I then have the Jquery code that I am attempting to “connect” to #myImage below.
function carDirection(){
var currentPosition = $("#myImage").text(this.id + offset.left );
if ("#myImage" <= currentPosition){
$("#myImage").attr("src", "leftCar.png");
}
else {
$("#myImage").attr("src", "rightCar.png");
}
};
So to summarize and make this even clearer I am creating a div that is using JQuery’s draggable effect and I simply want an image that is wrapped in it to change depending on if the user drags it left or right with the mouse. The image should stay the same after the user lets go of the mouse.
Thank you.
You need to use the
dragcallback for.draggable()to determine if the car has moved left or right since last time.EDIT: Code updated to be a lot clearer with more comments.
jsFiddle example is available.
Note that you would be better to use CSS classes and a sprite image (a single image containing both left and right car images), as I believe changing the background position of the same image is faster for most browsers than changing the
src. Also, you only need to load one image, and so you don’t need to load the image for the other direction the first time it changes. Does that make sense?Is there anything else from my code that doesn’t make sense now?