jQuery UI: Draggable
Draggable Elements
by Matthew Day
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/overcast/jquery-ui.css">
<div id="viewport">
<div id="draggable" class="ui-widget-content">
<div id="the-image">
<img src="http://digital-photography-school.com/wp-content/uploads/flickr/5661878892_15fba42846_o.jpg" />
</div>
</div>
</div>
CSS
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#viewport {
border: 1px solid gray;
cursor: move;
height: 400px;
margin: 0 auto;
overflow: hidden;
width: 400px;
}
#draggable {
height: 100%;
}
.ui-widget-content {
}
.ui-draggable {
}
#the-image {
/* margin: 0 auto; */
overflow: hidden;
width: 40%;
}
/* #the-image.active {
overflow: hidden;
width: 800px;
} */
img {
/* display: block; */
/* height: auto; */
width: 100%;
}
/*
Add custom styling or use existing jQuery UI themes
REFERENCE: jQuery UI themes, http://blog.jqueryui.com/
*/
JavaScript
// call the draggable function on each id "draggable"
$("#draggable").each(function() {
$(this).draggable();
});
// add class "noclick" while <img> is being dragged
$('#draggable').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
/*
$('#the-image').click(function(event) {
// toggle class 'active' whenever <img> is clicked
$(this).toggleClass('active');
});
*/
$('#draggable').click(function(event) {
// toggle class 'active' whenever <img> is clicked
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
}
});
//set up width and height of draggable container according to viewport and draggable size
var dragContainerWidth = $("#viewport").innerWidth() + ($('#the-image').outerWidth() - $("#viewport").innerWidth()) * 2;
var dragContainerHeight = $("#viewport").innerHeight() + ($('#the-image').outerHeight() - $("#viewport").innerHeight()) * 2;
$("#draggable").css("width",dragContainerWidth);
$("#draggable").css("height",dragContainerHeight);
//set up position of draggable container according to view container and draggable size
var dragContainerOffsetLeft = $("#viewport").offset().left + $("#viewport").outerWidth()/2 + $("#viewport").innerWidth()/2 - $('#the-image').outerWidth();
var dragContainerOffsetTop = $("#viewport").offset().top + $("#viewport").outerHeight()/2 + $("#viewport").innerHeight()/2 - $('#the-image').outerHeight();
$("#draggable").offset({left:dragContainerOffsetLeft,top:dragContainerOffsetTop});
$('#the-image').draggable({containment:"#draggable"});
/* see http://stackoverflow.com/questions/1771627/preventing-click-event-with-jquery-drag-and-drop */