June 26, 2012
How to restrict the div to margin right or left
Question by Rana Muhammad Usman
I have created a custom scroll. In which I am shifting the contents right and left by increasing or decreasing the margin. I want to restrict the div not to margin more when the last or first content is visible or you can say I want to make it like scroll. How I can restrict the div not to move anymore
$('#left').live('click' , function(){
$('#myDiv').css("margin-left","-=10px");
})
$('#right').live('click' , function(){
$('#myDiv').css("margin-left","+=10px");
})
Answer by Starx
Define and maximum limit for margin left or right, then use this value to compare before changing its position.
var maxMargin = 500, minMargin = 20;
$('#left').on('click' , function(){
if($('#myDiv').css("marginLeft") > minMargin) {
$('#myDiv').css("margin-left","-=10px");
}
});
$('#right').on('click' , function(){
if($('#myDiv').css("marginLeft") < maxMargin) {
$('#myDiv').css("margin-left","+=10px");
}
});