Reputation: 44293
probably a simple task, but I don't know how to approach this.
I have a huge image (the image is dynamic and has different widths and heights) and I want it to always load centered vertically and centered horizontally on my page.
the image is always too big for the body to cover it so it overflows the page, but that is exactly what I want and need.
TASK 1.) I just need to automatically position it with the center of the image always vertically and horitontally centered within the body.
TASK 2.) I want the image to be draggable, but exactly to its boundries. So I want the image to be dragged till I for instance reach the upper right corner and it hits the corner of the viewport, but I don't want it do be draggable further.
-> http://jsfiddle.net/3j40b4u1/
<div class="container">
<img class="draggable" src="http://upload.wikimedia.org/wikipedia/commons/b/ba/Flower_jtca001.jpg" alt="image"/>
</div>
So this should not be possible … https://s3.amazonaws.com/f.cl.ly/items/3p2P222S2d163N1R0v2M/Screen%20Shot%202015-03-04%20at%2018.53.47.png
This is what should be possible … https://s3.amazonaws.com/f.cl.ly/items/1i3o462l2Z3t3t3z1v0m/Screen%20Shot%202015-03-04%20at%2018.54.42.png
How would i do this?
Thanks in advance, Matt
Upvotes: 0
Views: 47
Reputation: 950
It's not so simple to achieve it, but let us try. First we need to inject code to our "drag" event, we force it not to go out of our boundaries:
drag : function(e,ui) {
//Force the helper position
if (ui.position.left > 0) {
ui.position.left = 0;
}
if (ui.position.top > 0) {
ui.position.top = 0;
}
}
Then the second part, centering an image. You can achieve it in dozens of ways - all you have to remember is to invoke it on "create" event of our draggable method:
create: function (event, ui) {
var img = $(".draggable")
, imgWidth = img.width()
, imgHeight = img.height();
img.css("position","absolute");
img.css("top", Math.min(0, ($(window).height() - imgWidth / 2) +
$(window).scrollTop()) + "px");
img.css("left", Math.min(0, ($(window).width() - imgHeight / 2) +
$(window).scrollLeft()) + "px");
}
Here, that's all! Not so complicated.
http://jsfiddle.net/3j40b4u1/4/
Upvotes: 1