Reputation: 4801
I have a draggable element within a container and i need that element to always be visible;
The width and height of the element are higher that the container w/h
If the left
value goes under -2000px I need it to stay at -2000px
<style>
#draggable {
width: 3000px;
height: 2100px;
}
</style>
<script>
$(function() {
$("#draggable").draggable();
$("#draggable").on('change', function(e) {
var left = $('@draggable').css('left');
left = left.replace ( /[^\d.]/g, '' );
console.log(left);
if (left < -2000) {
$('#draggable').css('left', '-2000px');
}
}
);
});
</script>
<div style="position:relative; width:1000px; height:700px; background:#ff0000; margin:0 auto; overflow: hidden;">
<div id="draggable" class="ui-widget-content" style="position:relative; width:3000px; height:2100px; overflow: hidden; left:0px; top:0px;">
content goes here
</div>
</div>
Upvotes: 0
Views: 37
Reputation: 577
The issue is that you are trying to compare a string value against an integer value in your IF statement? Check the type of 'left' with:
console.log(typeof left)
You have the following line that modified the variable left, but it still remains a string type:
left = left.replace ( /[^\d.]/g, '' );
Change that to this to convert it into it's integer equivalent:
left = parseInt(left.replace ( /[^\d.]/g, '' ));
The replace() function in javascript searches a string value for a specified substring and replaces it with something else, which keeps it as a string value, and not as an integer, what you need.
Upvotes: 0
Reputation: 1279
There are two issues with your code.
The first issue is that you're not listening for the correct jQuery event. Instead of listening for on('change'..)
, you should define a stop:
handler in the .draggable()
call.
The second issue is that your replace
statement is also removing the minus sign from the number of pixels. The parseInt
method will work.
Fixing both of those issues, your code should look like this:
$(function() {
$("#draggable").draggable({
stop: function() {
var left = $('#draggable').css('left');
left = parseInt(left, 10);
console.log(left);
if (left < -2000) {
$('#draggable').css('left', '-2000px');
}
}
});
});
Here's the fiddle I made to test out this code: http://jsfiddle.net/a9pp7hpk/
Upvotes: 1