Devrim Devrim - 5 months ago 14
jQuery Question

jQuery: Inaccuracy with scrollLeft when scaled

I have a scrollable container with links and thumbnails - scrollLeft to thumbnail depending on the link clicked which works fine, normally.

However, when I scale the main container with transform, scrollLeft scrolls to wrong position.

Any ideas how to resolve this?

scroll: function(){
var chapterName = this.chapter.getAttribute('data-chapter');
var thumbnail = $('.thumbnail-content[data-chapter="'+chapterName+'"]').parent();
if ( !$(this.chapter).hasClass('active-chapter') ){
$('.active-chapter').removeClass('active-chapter');
$('#thumbnail-container').animate({
'scrollLeft' : '+='+thumbnail.position().left
},{
duration : 400,
easing : 'easeOutSine'
});
$(this.chapter).addClass('active-chapter');
}
}

reScale: function() {
var windowHeight = $(window).height() - 20;
if (windowHeight <= 827) {
$('#viewer-container').addClass('scale scale075');
}
}


CSS:

.scale075 {
-webkit-transform: scale(0.75); /* Chrome, Safari 3.1+ */
-webkit-transform-origin: 50% 50%;
-moz-transform: scale(0.75); /* Firefox 3.5+ */
-moz-transform-origin: 50% 50%;
-ms-transform: scale(0.75); /* IE 9 */
-ms-transform-origin: 50% 50%;
-o-transform: scale(0.75); /* Opera 10.50-12.00 */
-o-transform-origin: 50% 50%;
transform: scale(0.75); /* Firefox 16+, IE 10+, Opera 12.10+ */
transform-origin: 50% 50%;
}


Here is a fiddle

Answer

You can resolve this if you know the scale in the script. I modded your fiddle to fix it and tried to fix your example code.

Here is a fiddle

So when you transform to say 0.75 you set a variable to 0.75 then when you set the scrollLeft you multiply the thumbnail position with 1/scale

var scrollScale = 1;

...

scroll: function(){
  var chapterName = this.chapter.getAttribute('data-chapter');
  var thumbnail = $('.thumbnail-content[data-chapter="'+chapterName+'"]').parent();
  if ( !$(this.chapter).hasClass('active-chapter') ){
    $('.active-chapter').removeClass('active-chapter');
    $('#thumbnail-container').animate({
      'scrollLeft' : '+='+thumbnail.position().left * (1/scrollScale)
    },{
      duration : 400,
      easing : 'easeOutSine'
    });
    $(this.chapter).addClass('active-chapter');
  }
}

reScale: function() {
  var windowHeight = $(window).height() - 20;
  scrollScale = 1;
  if (windowHeight <= 827) {
    $('#viewer-container').addClass('scale scale075');
    scrollScale = 0.75;
  }
}

Hope that solves your problem or give you an idea how to solve it more dynamically.

So the reason for this is that position().left uses your transform when it recalculates position.. But scrollLeft dont check transform. so you recalculate position so they use the same scale.

Comments