1

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.

0

1 Answer 1

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 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.