5

Is it possible to trigger the media query @media (max-width: 600px) { .a { ... } } when clicking on a button with Javascript ? (without having the browser width really < 600px)

// $('#b').click(function(){ // trigger the media query });
.a { background-color: green; }

@media (max-width: 600px) { 
    .a { background-color: yellow; /* many other rules */ }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a">Hello</div>
<input id="b" type="button" value="Change" />

1 Answer 1

7

You cannot trigger media query styles with JavaScript, but you can enable them by using a separate stylesheet and modifying its media attribute. Here is what I mean:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" media="all" href="regular_styles.css">
    <link rel="stylesheet" media="(max-width: 600px)" href="small_screen.css" id="small">
</head>
<body>

    <div class="a">Hello</div>
    <input id="b" type="button" value="Change" />

    <script src="jquery.min.js"></script>
    <script>
        $('#b').click(function(){
            // set the media query perimeter to "all"
            $('#small').attr('media', 'all');
        });
    </script>
</body>
</html>

regular_styles.css

.a { background-color: green; }

small_screen.css

.a { background-color: yellow; /* many other rules */ }
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.