Reset css or script on browser resize

It might be difficult to explain, but tell me that my browser is small, as in image 1. The bottom text is positioned where it should be and when I scroll down the script is activated.

EDIT https://jsfiddle.net/j4f53rds/1/

function fixDiv() {
    var $div = $("#nav_color");
    var top = $div.data("top");
    if ($(window).scrollTop() > top) {
        $('#nav_color').css({'position': 'fixed', 'top': '0px'}); 
    }
    else {
        $('#nav_color').css({'position': 'absolute', 'top' : top + 'px'});
    }
}

$("#nav_color").data("top", $("#nav_color").offset().top); 
$(window).scroll(fixDiv);

      

The script causes the text at the bottom to become fixed at the top of the html when the user scrolls down. Now here's the question. After firing, if I resize the browser, say make it full screen like in image two, then scroll back. The text is not rearranged as this will be a new location, it is reset back to its original position in the smaller browser. How do I get the script to take into account the new browser size when the user scrolls through the backup?

enter image description here

enter image description here

+3


source to share


4 answers


The problem is that you keep the top position on page load, but that position changes when the window is resized. Try the following:



$(window).resize(function() {
    $("#nav_color").data("top", $("#nav_color").offset().top); 
    fixDiv(); //not sure if you need this.
});

      

+2


source


The problem is that you top:

inline CSS property sticks to the element #nav_color

and is not recalculated when resized,

try this (variable definition top

is still not perfect.):



var top = $("#nav_color").offset().top; 

function fixDiv() {
    var $div = $("#nav_color");
   // var top = $div.data("top"); shouldn't define it here  
    console.log(top);
    if ($(window).scrollTop() > top) {
        $('#nav_color').css({'position': 'fixed', 'top': '0px'}); 
    }
    else {
        $('#nav_color').css({'position': 'absolute', 'top' : top + 'px'});
    }
}
$(window).scroll(fixDiv);

function positionDiv() {
    top = ($(window).innerHeight())*0.86;
    if ($("#nav_color").css('position') == 'absolute'){
        $("#nav_color").css({ 'top': top });
    }

}
$(window).resize(positionDiv);

      

violin

+1


source


You need to call a function on window.resize

You can call your function like this:

$(window).resize(function(e) {
    $("#nav_color").data("top", $("#nav_color").offset().top()); 
    fixDiv(); //not sure if you need this.
});

      

0


source


This should work:

$addHandler(window, "resize", fixDiv);

      

Every time the user resizes the window, the fixDiv funcion will run

0


source







All Articles