Reputation: 16335
When #right
element is dragged, I want to resize its parent. My example works incorrectly and I'm failing to comprehend why. Any hints how to fix it?
Just in case, what I'm trying to do here is to create a resizable scroll similar to this one. But for now, I'm only interested in the right element.
Upvotes: 4
Views: 201
Reputation: 818
The simplest solution is as follows (note the #left and #right changes in SCSS):
SCSS:
#container {
width: 500px;
height: 100px;
background: #f9f9f9;
}
#nav {
width: 100px;
height: 100px;
background: #e9e9e9;
cursor: move;
}
#left {
width: 10px;
height: 100px;
position: absolute;
top:0;
left:0px;
background: #a9a9a9;
cursor: w-resize;
&:hover {
background: #999;
}
}
#right {
width: 10px;
height: 100px;
position:absolute;
top:0;
right:0px;
background: #a9a9a9;
cursor: e-resize;
&:hover {
background: #999;
}
}
JavaScript:
var cont = $("#container")
var nav = $("#nav")
var left = $("#left")
var right = $("#right")
nav.draggable({
containment: cont
});
right.draggable({
containment: cont,
drag: function(e, ui) {
nav.width(ui.position.left);
}
});
The only problem was you were getting too fancy with your JavaScript. The ui.position.left had all the information you needed. All I did was change the content from floating to position:absolute;
Upvotes: 3
Reputation: 94299
You can use the good ol' pure JavaScript to do that
http://jsfiddle.net/DerekL/cCvGD/
var oriX = 0,
oriW = 0,
mousedown = false;
right.mousedown(function (e) {
oriX = $(this).offset().left; //store the initial x and width
oriW = nav.width();
mousedown = true; //mousedown sets to true
e.stopPropagation(); //prevent nav from being dragged
})
$(window).mousemove(function (e) {
if(mousedown == true) { //only when mouse is down (dragging)
nav.width(oriW + (e.clientX - oriX)); //calculate the width
}
}).mouseup(function () {
mousedown = false; //mousedown sets to false
});
Both left and right: http://jsfiddle.net/DerekL/cCvGD/1/
Upvotes: 2
Reputation: 661
The problem is that the you are changing the width of your nav container, and this is moving out the right element. So while you are dragging it, it moves twice as far.
You can get get around this by resetting the location of your right element in the dragable method
right.draggable({
containment: cont,
drag: function(e, ui){
dragged = ui.position.left;
nav.width(originNavWidth + dragged);
ui.position.left = nav.position.left;
}
})
see: http://jsfiddle.net/vf4eS
Upvotes: 1