Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't window.onresize working? (javascript/jquery)

I'm trying to make this site show a tab-box on large screens, but just a normal layout on smaller screens. Here's what I have:

function adapt() {
if(document.documentElement.clientWidth > 800) {

    $(document).ready(function() {

        $(".box").hide();
        $(".box:first").show(); 

        $("ul.tabs li").click(function() {
            $("ul.tabs li").removeClass("active");
            $(this).addClass("active");
            $(".box").hide();
            var activeTab = $(this).attr("rel"); 
            $("#"+activeTab).show(); 
        });
    });

}else{
    $(document).ready(function () {
        $('.box').show();
    });
};}

window.onload = adapt();
window.onresize = adapt();

The onload event handler works, so the tab-box jquery function only works if the page is loaded on a larger screen, and it shows all the content when loaded on a smaller screen. I added the onresize event so it would also change when the browser window is shrunk down, but it doesn't work. If I load on a large screen and then shrink it, all that shows is the content that was in the first tab, and if I load on a small screen, and then make the window bigger, all the content is displayed and the tab buttons don't work. Am I just misinterpreting how window.resize is supposed to work?

I'm guessing that maybe the event only fires once the first time the resize occurs, and if the difference isn't enough that time for my other conditional to take over, it doesn't happen. If this is the case, is there a way to make it continually check for screen size, like with CSS media queries?

like image 832
Nathan Avatar asked Apr 10 '15 11:04

Nathan


3 Answers

don't forget, that if some other code in your project also uses window.onresize or window.onload - your code will be overwritten

it's a better practice to use addEventListener function

window.addEventListener('resize', adapt);
like image 129
v1vendi Avatar answered Oct 08 '22 01:10

v1vendi


You need to call the reference, not execute the function

window.onload = adapt;
window.onresize = adapt;

Because when you do

window.onload = adapt();
window.onresize = adapt();

You execute adapt() and since it return nothing, you have nothing done on these events

like image 42
romuleald Avatar answered Oct 08 '22 02:10

romuleald


You can try with jquery:

$(document).ready(function() {
    adapt(); // onload
    $(window).resize(adapt()); // resize
});
like image 1
JanSLO Avatar answered Oct 08 '22 01:10

JanSLO