In this post, we will learn how to use media queries with JavaScript. Media queries was introduced in CSS3 and this is a masterpiece for Responsive Web Design. So how we can use media queries with JavaScript, we will learn in this post.


How To Use Media Queries With JavaScript ?


Use Media Queries With JavaScript

To use media queries with JavaScript, we use  window.matchMedia()  method. This method takes parameter like CSS @media rule like max-width, min-height etc. So how we can use this JavaScript method, we see in following example.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Use Media Queries With JavaScript ?</title>
</head>
<body>


<p>If the browser window width will be less than or equal to 600px, then h1 heading color will be blue otherwise color will be black.</p>


<h1>CodexRadar</h1>


<script>
function changeColor(detectMedia) {
if (detectMedia.matches) {

// If media query matches then color will be blue
document.getElementsByTagName("H1")[0].style.color = "blue";
} else {

// If media query doesn't match then color will be red
document.getElementsByTagName("H1")[0].style.color = "red";
}
}


// Apply JavaScript Method
var detectMedia = window.matchMedia("(max-width: 600px)");


// Call function
changeColor(detectMedia);


// Attach listener function on state changes
detectMedia.addListener(changeColor);
</script>


</body>
</html> code-box


Summary

In this post we learned how to use media queries with JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post