Skip to content Skip to sidebar Skip to footer

Center An Element In Middle On Screen For An Horizontal Scroll List

I'm attempting to have the element clicked being positioned automatically at the center of the screen. The list is having a horizontal scroll with some overflow-x : scroll which is

Solution 1:

Its a little tricky, but here's the solution.

var left = $(this).offset().leftvar width = $("#timepicker").width();
  var diff = left - width/2
  $("#timepicker").scrollLeft($("#timepicker").scrollLeft()+diff)

Basically what i've done is get the present left position of the clicked element and divide it with half of the width of the container. This gives the difference which the scroller has to move in order to take the elment to the middle. Hope you understood the logic.

Here's the codepen attached http://codepen.io/prajnavantha/pen/eNwWgx

You can copy paste this in the code pen click handler and see it working.

Solution 2:

try this

 $('#timepicker li').on('click',function(){

  var pos=$(this).position().left; //get left position of livar currentscroll=$("#timepicker").scrollLeft(); // get current scroll positionvar divwidth=$("#timepicker").width(); //get div width
  pos=(pos+currentscroll)-(divwidth/2); // for center position if you want adjust then change this

  $('#timepicker').animate({
            scrollLeft: pos
  });

});

Post a Comment for "Center An Element In Middle On Screen For An Horizontal Scroll List"