Basj
Basj

Reputation: 46493

Trigger a media query with javascript

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" />

Upvotes: 5

Views: 3580

Answers (1)

blex
blex

Reputation: 25634

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 */ }

Upvotes: 7

Related Questions