HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Div circular scroll

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
circulardivscroll

Problem

Have one div:

Here's what scrolling of this div should look like:

The only way I see is to duplicate div to left and right sides of original one, and then scroll the whole bunch. Here is a corner-cutting implementation sketch: Fiddle



$(document).ready(function() {
$original = $("#original");
// Duplicate div to the left and right of original
$original.clone().attr("id", "left").prependTo("#scroll");
$original.clone().attr("id", "right").appendTo("#scroll");

// Set according width to parent we are going to scroll
w = $original.width();
$scroll = $("#scroll");
$scroll.width(w * 3);

// Radio button
$left_rb = $("#left_rb");

function roll_it() {
dest_pos = 0;
// Check radion button
if ($left_rb.prop("checked")) dest_pos = -2 * w;
// Set start position
$scroll.css('left', -w + 'px');
// Roll it
$scroll.animate({
left: dest_pos + "px"
}, 1000, "linear", roll_it);
}

roll_it();
});

.scrollable {
width: 150px;
height: 50px;
float: left;
}
#container {
width: 150px;
height: 50px;
overflow: hidden;
}
#scroll {
position: relative;
}









Direction:

<<<<<
>>>>>




Any better way? Existing plugins (it should be scrollable to any choosen position, not just slideshow)?

Solution

Be sure to localize all of your variables using var.

JavaScript naming using interCaps is more idiomatic than under_scores.

For a better user experience, use ` tags on your radio buttons. That makes the ">>>>>" text part of the control, for a larger click target.

If you are willing to change the semantically significant
tag into a purely decorative background-image, then the code can be greatly simplified through the use of background-repeat: repeat-x.



$(function() {
var $scroll = $(".scrollable");
var w = $scroll.width();
var pos = 0;

// Radio button
var $left_rb = $("#left_rb");

function rollIt() {
var movement = $left_rb.prop("checked") ? -w : w;
pos += movement;

$scroll.animate({
backgroundPosition: pos + "px"
}, 1000, "linear", rollIt);
}

rollIt();
});
.scrollable {
width: 150px;
height: 50px;
background-repeat: repeat-x;
}
#scroll {
background-image: url(//i.stack.imgur.com/vvcpe.gif);
}


Direction:

<<<<<
>>>>>
`

Context

StackExchange Code Review Q#98502, answer score: 2

Revisions (0)

No revisions yet.