0

Abridged Codepen below. I'm trying to model a page after this BBC article from way back, but I can't seem to get my image to go to position fixed based off scrolling.

I'm thinking that if I can get the element to be position: fixed then I can swap out the images with js

I can't seem to get my yPosition var to pass through my scroll function though http://codepen.io/spkellydev/pen/aWzwdQ?editors=1111

Here's the fuller codepen of the project, I just can't seem to get this js to work for me. Any tips?

here's my JS

var yPosition = document.getElementById("scrollLock").offsetTop;



window.onscroll = function(){ // scrolling fires this function      
console.log(yPosition);
    var myElement = document.getElementById("scrollLock"); // for cleaner code

    // compare original y position of element to y position of page
  console.log('it is scrolled at');
    if( yPosition < window.pageYOffset ){ 

        // snap element to the top by changing css values of element
        myElement.addClass('addScrollLockImg'); 
        console.log('it worked');
     } else {          

        // re-position to original flow of content
       myElement.removeClass('addScrollLockImg');
       console.log('it passed');
    }               
}      
Sean Kelly
  • 901
  • 7
  • 27
  • Have you not made a mistake with `myElement.addClass('addScrollLockImg'); `? It's a Jquery function and it seems that myElement is not a Jquery object since you get it with `document.getElementById("scrollLock");`. Maybe do `myElement = $(myElement);` – Mohicane Apr 14 '17 at 08:21

1 Answers1

-1

Have you tried using position: sticky ?

This doesn't directly answer your question but will produce exactly what you are looking for. Sticky is not fully supported though.

position: -webkit-sticky
position: sticky
top: 20px /* Distance from top of screen when 'stuck' */

This is all you need and it will keep it's place on the screen where the parent element allows. As in it will not move outside of it's parent element.

Your CodePen edited (I may have messed up some of your CSS)

Lou Bagel
  • 1,001
  • 8
  • 11
  • I decided to go with the position: sticky even though the browser support is pretty bad. One day I'll go through and make it proper. Thanks for the tip – Sean Kelly Apr 16 '17 at 04:12