Nathan
Nathan

Reputation: 2387

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?

Upvotes: 10

Views: 13989

Answers (3)

v1vendi
v1vendi

Reputation: 613

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);

Upvotes: 26

JanSLO
JanSLO

Reputation: 388

You can try with jquery:

$(document).ready(function() {
    adapt(); // onload
    $(window).resize(adapt()); // resize
});

Upvotes: 2

romuleald
romuleald

Reputation: 1434

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

Upvotes: 15

Related Questions