Question

I am trying to reveal an image on scroll on a px by px basis. Similar to how this site animates the red line, http://www.teslamotors.com/goelectric#. The image needs to be hidden in the same manor, so if the user scrolls up, they will see less of the line.

I feel like I am getting close but my javascript is not quite up to snuff. Here is a url of what I have done so far, http://trippruitt.com/fuckinLineAnimationBullshit/, and here is my script. Any help will be very much appreciated, thanks!

init();

/*==========  init calls all custom functions  ==========*/
function init() {

    $(window).on("scroll", scrolling);
    console.log("init works");
}
/*==========  ==========  ==========*/


/*==========  get scrollTop  ==========*/
function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers except IE before #9
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}
/*==========  ==========  ==========*/


/*==========  scrolling function  ==========*/
function scrolling() {

    console.log(getScrollTop());

    if (getScrollTop() > 64) {
        addHeight();
    }
}
/*==========  ==========  ==========*/


/*==========  add height to line  ==========*/
function addHeight() {

    $(window).on("scroll", function() {
        var i = 0,
            line = $(".fuckinLine");
        while (i < 209) {
            line.css("height", i++ + "px");
            event.preventDefault();
            console.log("addHeight works");
        }
    });
}
/*==========  ==========  ==========*/ 
Was it helpful?

Solution

Your problem lies here:

function addHeight() {

    $(window).on("scroll", function() {
        var i = 0,
            line = $(".fuckinLine");
        while (i < 209) {
            line.css("height", i++ + "px");
            event.preventDefault();
            console.log("addHeight works");
        }
    });
}

You had already set an event for $(window).on("scroll", function() { in the init function. By doing this you were essentially doing the addHeight function twice every time the window scrolled.

This should work for you:

/*==========  scrolling function  ==========*/
function scrolling() {

    console.log(getScrollTop());
    addHeight(getScrollTop());
//Great place for logic to addwidth to make the line move horizontally.
}
/*==========  ==========  ==========*/


/*==========  add height to line  ==========*/
function addHeight(newHeight) {
    $(".fuckinLine").css("height", newHeight + "px");
}
/*==========  ==========  ==========*/

Notice I also removed the while loop. This will keep the div from growing to the max height after one scroll. We only want this to expand 1px for each pixel down the window scrolled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top