user1459234
user1459234

Reputation: 13

JQuery on initial browser width not working properly (only works when resized)

The code below is used as an alternative to using media queries for browser width and modifying the css file for various moble widths. However, when the code is run for the furst time (when the website loads), the condition: (width >= 767) && (width < 1042) loads first on all widths less than 1042. For instance, if the width is 400, the medium2.css will be used.

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 1042) {
        $(".leftNavigationBox").hide();
    }
    if (width < 440) {
        $(".container").hide();
        $("#sizestylesheet").attr("href", "/Styles/Reallynarrow3.css");
    } else if ((width > 441) && (width < 767)) {
        $(".container").hide();
        $("#sizestylesheet").attr("href", "/Styles/narrow2.css");
    } else if ((width > 768) && (width < 1042)) {
        $(".container").hide();
        $("#sizestylesheet").attr("href", "/Styles/Medium2.css");
    } else {
        $(".leftNavigationBox").show();
        $(".container").show();
        $("#sizestylesheet").attr("href", "/Styles/SiteNew28.css");
    }
}

$(function () {
    adjustStyle($(this).width());
    $(window).resize(function () {
        adjustStyle($(this).width());
    });
});

Upvotes: 0

Views: 103

Answers (1)

Moob
Moob

Reputation: 16184

$(this) refers to the jQuery object to which the event or method is attached.

$(function(){ is shorthand for $(document).ready(), so on the first call $(this) refers to the document. On resize $(this) refers to the window.

To fix the issue, simply pass the $(window).width() rather than $(this) to your adjustStyle() method on first call.

$(function () {
    adjustStyle($(window).width());
    $(window).resize(function () {
        adjustStyle($(this).width());
    });
});

Upvotes: 1

Related Questions