0

I have been toying around with the JSFiddle found from the answer to this question. My problem is similar, except the div that I want to have scroll only a certain way down the page is supposed to be vertically centered on the left side of the window, not in the top-left corner. I tried making this modification to the JQuery:

    $.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 50%
            });
        }
    });

But when I set top: 50% in the else, the scrolling doesn't stop at the specified pos and instead follows all the way down the page. Here's my full modified JSFiddle.

How do I properly modify this so that I can have the element fixed centered halfway vertically, but stop after a certain point?

  • can you explain a bit more – Sagar Sinha Jul 20 '17 at 18:29
  • I want the div which follows as you scroll to stop following at a certain point `pos`, which is an argument to the `followTo` function. If you look at the original JSFiddle, the div will stop following at whatever pos you specify. But in my JSFiddle, it doesn't stop when it passes pos. In the original it sets `top` to 0 if the scrolltop hasn't hit `pos` yet, but in mine I set it to 50% to keep it vertically centered in the window. – Kaisermania Jul 20 '17 at 18:32
  • you can use height in pixel. http://jsfiddle.net/Tgm6Y/11650/ – Sagar Sinha Jul 20 '17 at 18:47

1 Answers1

0

The first problem is you need to put your 50% in quotes, there was an error when ran. The second issue is that when you set it to pos after you hit the 2000 mark it would jump out of view, so you need to get your window height and set it to pos + windowHeight/2. Here is your updated code

var windw = this;

$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(window);

    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos + ($(window).height() / 2)
            });
        } else {
            $this.css({
                position: 'fixed',
                top: '50%'
            });
        }
    });
    };

    $('#f').followTo(2000);

and your updated fiddle http://jsfiddle.net/Tgm6Y/11649/

CumminUp07
  • 1,936
  • 1
  • 8
  • 21