jmgibbo
jmgibbo

Reputation: 97

jQuery drag image under another image

I need to drag an image that is currently under another png image.

I thought I could do this easily by using this code:

$(document).ready(function() {
    $(".imageOverlay").mousedown(function(eventObject){
    $('#draggable').drag();
    return false;
    });
});

However it doesn't seem to work.

You can find an example without the overlying image here

And here is the example with the overlying image here

Any help would be great, please keep your answers relatively simple as I am no guru in jQuery.

Thank you.

Upvotes: 0

Views: 516

Answers (2)

jmgibbo
jmgibbo

Reputation: 97

I managed to get this working by taking the width, height and positioning of the draggable object and giving the underlaying image the same css positioning, width and height.

This is the code:

    var imgdrag = $(#draggable); //This is the box you drag
    var imgselector = $(.imageUnderlay); //This is the image underneath

    //Get the height, width and position of the draggable box
    var height = imgdrag.height();
    var width = imgdrag.width();
    var top = imgdrag.css("top");
    var left = imgdrag.css("left");

    //Add the css style to the image underlay
    imgselector.css('top', top);
    imgselector.css('left', left); 
    imgselector.css('height', height + 'px'); 
    imgselector.css('width', width + 'px');

Upvotes: 1

Shahan Khan
Shahan Khan

Reputation: 16

Do this instead: listen to the onmousedown, onmousemove, onmouseup events on #container. Bind to the events using jQuery. When onmousedown occurs, and onmousemove fires, use e.pageX, e.pageY, and $('#container').offsetLeft and $('#container').offsetTop for the position, and set the new location for the underlying image. The moving logic should be on onmousemove if you want the user experience to be responsive (underlying image moves with cursor). Stop moving the underlying image when onmouseup fires.

Check out the following for an example:

Jquery mousedown + mousemove

Bottom of this page has an example of getting mouse position within the container (e.pageX, e.pageY, $('#container').offsetLeft and $('#container').offsetTop):

http://docs.jquery.com/Tutorials:Mouse_Position

Shahan

Upvotes: 0

Related Questions