Search code examples
javascriptjquerycssmatchmedia

Conditional Media Queries window.matchMedia


I am working with window.matchMedia(), and I cannot seem to get the function to apply a secondary class when a max or min width is reached. I've recreated the problem below with a simple font-size change.

I've read up on matchMedia() and I've tried this two different ways (both are included below). Do I need to include both a min and max value in order to have the function execute? Or am I missing something within the actual structure of the function itself?

$(document).ready(function() {
	
	var mq = window.matchMedia('(max-width: 700px)');
	
	if( mq.matches ) {
		$('.title').addClass('big')
	} else {
		$('.title').removeClass('big');
	}
});


/*
Second method I tried

$(function() {
 if( window.matchMedia('(max-width: 700px)').matches){
		$('.title').addClass('big')
	} else {
		$('.title').removeClass('big');
	}

});


*/
.title {
	font-size: 20px;
}

.big {
	font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="title">This is a title</h1>


Solution

  • It is working, maybe you are expecting it to detect screen resize? You have it bound to document.ready() so you have to refresh the page to see it.

    Try it out:

    • Make windows smaller than 700px, refresh
    • make window larger then 700px, refresh
    • Notice difference :)

    In another words:

    $(document).ready(your function)
    

    Your function only executes once for each time page is loaded.

    Alternatively, use this fiddle and run it. Make result window larger or smaller than 700px and run it again.

    If you need to run it every time when window width resizes I would recommend binding to window.onresize as I did in this fiddle with execution on resize event

    Notice the console.log I put there for you to see how and when it is triggered, you wanna remove it before going production ;)