How to use jQuery draggable with fixed position?
Asked Answered
H

3

10

It works perfect in firefox, but in ie, chrome and opera it doesn't work.

<div> has position:fixed, and is .draggable()

and it doesn't work except firefox

Hawkes answered 4/8, 2010 at 11:6 Comment(4)
Surely, you can't want it to be draggable and stay in the same position? You'll rip your screen off.Insurgent
I can. I want it be "fixed" in view port, but I also be able to move it a little bit right or left (draggable), and if i drop it, it should be "fixed" in the new position.Hawkes
I get identical behaviour in Chrome and FF: hereInsurgent
sje397's code works for me too in IE8 and Opera 10.6 but the element sticks to the bottom because of the css. If you specify a top and left then everything works normal.Ramification
E
12

don't set fixed in CSS: it works in firefox, chromium, safari, iexplore

var div = $('#id');
div.resizable(
{
    stop: function(event, ui)
    {                       
        var top = getTop(ui.helper);
        ui.helper.css('position', 'fixed');
        ui.helper.css('top', top+"px");         
    }       
});
div.draggable(
{
    stop: function(event, ui)
    {           
        var top = getTop(ui.helper);
        ui.helper.css('position', 'fixed');
        ui.helper.css('top', top+"px");
    }
});

function getTop(ele)
{
    var eTop = ele.offset().top;
    var wTop = $(window).scrollTop();
    var top = eTop - wTop;

    return top; 
}
Eldin answered 20/4, 2012 at 13:14 Comment(2)
Nice ! you can also use position:fixed; to initialise with a relative position and fixes the first drag jump jsfiddle.net/dX8N3/24Goby
do not forget to add jquery.ui (otherwise, you will get an error TypeError: $(...).resizable is not a function ;)Marketplace
B
1

Just use in your CSS:

#draggable{
    position:fixed !important;
}

If you are using both draggable and rezisable delete the "!important" from the CSS, and then set the stop option (the callback when the dragging and resizing stops) to this function:

function stop(event){
    if(event.type === "resizestop"){
        var topOff = $(this).offset().top - $(window).scrollTop()
        $(this).css("top",topOff)
    }
    $(this).css("position","fixed")     
}   
Bedfast answered 10/6, 2012 at 5:49 Comment(0)
B
0

if you put a break point on the ...draggable(...); you'll see that it is added position:fixed to the element.style.

just undo that with .style.position ="";

my code clears the style so it would fall back on the css declaration. with older jquery ui version, you may need to do the drag stop handler. which i doubt. but definitely not true for the latest.

Brass answered 4/10, 2019 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.