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");

})

JS Fiddle

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");
    }
});

And use .on() rathan than .live(), as it has been deprecated.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!