Dan382
Dan382

Reputation: 986

jQuery window width not working as expected

I'm making a responsive website that implements Javascript functions if the browser has a screen width of less than 'x' px.

However the code I've made only seems to work if the window with is true when the page initially loads, not if the browser is resized at a later point e.g.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function() {
    if ($(window).width() < 500) {
        $("#foo").css("background-color", "red");
    }
});
</script>
</head>

<body>
<div id="foo" style="height: 100px; background-color:blue;"></div>
</body>
</html>

In this example background the background-color remains blue if the browser is < 500px, if the browser originally loaded the content at 501px or more. I want to be able to resize the browser and trigger the Javascript in real time.

Any advice is appreciated.

Upvotes: 1

Views: 2895

Answers (1)

.resize()

$(function () {
    $(window).resize(function () { //put your code in window.resize so that it runs when ever window is resized
        if ($(window).width() < 500) {
            $("#foo").css("background-color", "red");
        }
    }).resize(); //call resize function 
});

Upvotes: 1

Related Questions