Sliding a div using jQuery scrollleft
10,574
Solution 1
I agree about the use of Animate. Here's a link to a fiddle that I created starting with your code: link
$(document).ready(function () {
$("#left").click(function () {
$("#cont").animate({
left: '-=50'
}, 'slow');
});
$("#right").click(function () {
$('#cont').animate({
left: '+=50'
}, 'slow');
});
});
Solution 2
I think you should take the help of animate function, like this
$('#cont').animate({left:'+100px'}, 1000);
Author by
user2226161
Updated on June 04, 2022Comments
-
user2226161 almost 2 years
I'm pretty new to jQuery, so this is probably a noobish question. I want to move a div left and right, manually (not animated). Specifically, I want to be able to click a Left button, and it moves left 100px, or click a Right button, and it moves right 100px. I'm sure I'm missing something obvious (probably multiple obvious things), but I've done a lot of checking, and I haven't been able to find anything that helps. I am using the basically self-contained code below as a test. The div just doesn't move.
<!DOCTYPE HTML> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript"> $(document).ready( function() { $("#left").click( function() { var pos = $("#cont").scrollLeft()-100; $("#cont").scrollLeft(pos); }); $("#right").click( function() { var pos = $("#cont").scrollLeft()+100; $("#cont").scrollLeft(pos); }); }); </script> </head> <body> <div id="cont" style="position:relative; overflow:auto; width:400px; height:50px; border:10px solid #D6D6D6;"></div> <br /> <input type="button" id="left" value="Left"> <input type="button" id="right" value="Right"> </body> </html>
-
user2226161 about 11 yearsI appreciate the suggestion, but when I said "not animated" I really meant that. I know this will seem strange, but for the application I am trying to solve, I really want the div to instantly pop the 100px, not smoothly move the 100px. And I really need to see if I can do it with scrollLeft.
-
user2226161 about 11 yearsThis looks great, and I appreciate this too... But see my comment to the answer above. I really need it to instantly pop. Hopefully still using scrollLeft. If that's impossible, I will probably use your suggestion here. But I hope the instant pop with scrollLeft is actually possible.
-
David Tansey about 11 yearsInstant pop? You can do that. Where I specified
'slow'
and @ankitsrist specified1000
, simply change that value to1
...As in one millisecond -- then it should pop. Here's an updated fiddle -
Yogesh Nath over 10 years@DavidTansey how can I stop the the image/div from moving outside the left and right window? At present if you keep pressing 'left' and 'right' button the image/div goes out of the window. I hope you know what I mean.
-
Fanky almost 5 yearsthe 1000 in the end is time in ms
-
Fanky almost 5 yearsso you can replace it with zero. Same for scrollLeft.