I have an element where the jScrollPane
is being used to provide custom scrollbars for an extensive text. The idea behind the code is to change the image beside the text each time the user reaches a certain amount of scroll while reading the text.
To have the code flexible, I've prepared a method to detect the number of images available and from there establish the trigger points for the image change. This is all based on the text wrapper height.
Can't this be simplified, thus reducing the amount of code, perhaps in such reduction, have it improved?
HTML structure
<div id="imageWrap">
<img data-index="1" src="..." class="active" />
<img data-index="2" src="..." />
<img data-index="3" src="..." />
</div>
jQuery/JavaScript code
$imagesWrap = $('#imageWrap');
if ($imagesWrap.size()==1) {
//target all images and count them
var $targets = $imagesWrap.find('> img'),
total = $targets.size();
//for each found, set the CSS z-index
$targets.each(function(){
var $this = $(this),
index = $this.data('index');
//revert order
$this.css({
'z-index': total-index
});
});
var $scrollSpy = $('.jspPane'), //the element to spy
height = $scrollSpy.height(), //its height
stepsTrigger = parseInt(height/total), //trigger at "every" this distance
currentPos = 0; //current position (active image)
setInterval(function(){
//ascertain current position (insure positive number)
currentPos = Math.abs(parseInt($scrollSpy.css('top'), 10));
//ascertain the target image
var img = Math.round(currentPos/stepsTrigger),
id = img==0 ? 1 : img,
$tgt = $('img[data-index="'+id+'"]');
//if different from the already active
if (!$tgt.hasClass('active')) {
$imagesWrap.find('.active').removeClass('active').hide();
$tgt.fadeIn().addClass('active');
}
}, 100);
}