I am new to javascript and have come up with this counter Here is the JSFiddle - http://jsfiddle.net/ep6s616z/ and below is the javascript
I'm trying to figure out how i could add more values so that it goes up to 20 on the counter tool. It must stay the same size, so how could i achieve this?
Would the new values be hidden and slide in?
Any help would be much appreciated!
var pages = ["1", "2", "3", "4", "5", "6", "7", "8"];
$(document).ready(function () {
var num = 1;
updatePrice(num);});
function updatePrice(num) {
pages.forEach(function(entry) {
if (entry == num) {
document.getElementById(entry).className = "page-selected page";
}
else {
document.getElementById(entry).className = "page";
}
document.getElementById('circle').innerHTML = num });
}
function addOne() {
var current = document.getElementsByClassName('page page-selected')[0].id
if (current < 8) {
current++;
updatePrice(current);
}
}
function takeOne() {
var current = document.getElementsByClassName('page page-selected')[0].id
if (current > 1) {
current--;
updatePrice(current);
}
}
I did a complete re-write as the events are far cleaner in pure jQuery. I also added an extra div to allow the scrolling you wanted:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/ep6s616z/18/
Simpler HTML:
<div id="circle">1</div>
<div id="calculator">
<div id="slider-left">-</div>
<div id="slider">
<div id="page-holder"></div>
</div>
<div id="slider-right">+</div>
</div>
Code:
// Generate n items
for (var i = 1; i <= 20; i++) {
$('#page-holder').append($('<div>').addClass('page').text(i));
}
// Outer slider - allows for scroller
var $slider = $('#slider');
// Actual page holding div
var $pageHolder = $('#page-holder');
// Listen for clicks on any .page divs
$pageHolder.on('click', 'div.page', function (e) {
var $div = $(this);
$('#page-holder .page').removeClass('page-selected');
$div.addClass('page-selected');
$('#circle').html($div.html());
// Ensure the element is visible - of not scrill it into view
var offset = $div.offset();
// Range of the visible area
var areaStart = $slider.scrollLeft();
var areaEnd = areaStart + $slider.width();
var x = ($div.index() + 1) * $div.outerWidth();
if (offset.left > areaEnd)
{
$slider.animate({scrollLeft: x}, 100);
}
else if (offset.left < areaStart)
{
$slider.animate({scrollLeft: x-$div.width()}, 100);
}
});
$('#slider-right').click(function () {
var $div = $('#page-holder .page-selected');
if (!$div.length) {
$div = $('#page-holder .page:first');
} else {
$div = $div.next();
}
$div.trigger('click');
});
$('#slider-left').click(function () {
var $div = $('#page-holder .page-selected');
if (!$div.length) {
$div = $('#page-holder .page').last();
} else {
$div = $div.prev();
}
$div.trigger('click');
});
Note: the scrolling to keep it in view is not perfect, as the range checks are not quite right, but you need something to do. :)