Skip to content Skip to sidebar Skip to footer

Pop Up Text After Scrolling Certain Distances Is Not Working

I'm trying to get text to pop up at a fixed location at different y-scroll intervals however, I can't seem to chain the scripts correctly. It seems to skip the first action of disp

Solution 1:

Your functions should have different names. Try

var startY1 = 900;
var stopY1 = 1800;
var startY2 = 1801;
var stopY2 = 2500;

$(window).scroll(function(){
    checkY();
});

function checkY()
{
    console.log($(window).scrollTop()); 
    if($(window).scrollTop() > startY1 && $(window).scrollTop() <= stopY1)
    {
        console.log("Show"); 
        $('.foxedDiv').show(); 
    }
    else
    {
        console.log("Hide"); 
        $('.foxedDiv').hide();
    }

    if($(window).scrollTop() > startY2 && $(window).scrollTop() <= stopY2)
    {
        console.log("Show"); 

        $('.foxedDivved').show(); 
    }
    else
    {
        console.log("Hide"); 
        $('.foxedDivved').hide();
    }
}

checkY();

Fixed Fiddle:

http://jsfiddle.net/k8bnd/1/


Solution 2:

This is happening because you have overwritten the previous values/functions. To make this more dynamic you can add data-* attributes to each message element specifying which positions they are valid for. And then in the scroll event check each element's position data, if the window is within that range show it, otherwise hide it.

HTML

<!-- Changed the classes both elements had to foxedDiv
     so that we can select them as a group and loop over them -->
<div class="foxedDiv" data-position="900,1800">
    MESSAGE 1
</div>    
<div class="foxedDiv" data-position="1801,2500">
    MESSAGE 2
</div>

JS

//Note you do not need to make an anonymous
//function just to do the call for checkY
//just pass the function
$(window).scroll(checkY);

function checkY(){
    //save this value so we dont have to call the function everytime
    var top = $(window).scrollTop();
    console.log(top); 
    $(".foxedDiv").each(function(){
       var positionData = $(this).data("position").split(",");
       if(top > positionData[0] && top <= positionData[1]){
           console.log("Show"); 
           $(this).show(); 
       } else {
           console.log("Hide"); 
           $(this).hide();
       }       
    });
}
checkY();

JSFiddle Demo


Post a Comment for "Pop Up Text After Scrolling Certain Distances Is Not Working"