I'm trying this but it is not working:
<html>
<head>
<script src="js/menu-collapser.js" type="text/javascript" media="media screen and (max-width: 599px)"></script>
</head>
...
</html>
//menu-collapser.js :
jQuery(document).ready(function($){
$('.main-navigation li ul').hide();
$('.main-navigation li').has('ul').click(function() {
$(this).children().toggle();
});
});
Do you have an idea on how to do this in the right way? The script work if used directly in the header with the tags.
Why not just load in a script conditionally?
Or better yet, only execute the code if the window.innerWidth > 600 ? Anyway, there are a lot of solutions you can use.
media
is not a valid attribute for<script>
, check it here.So you should detect media types by manually than load the script dynamically.
There is a plug-in for css media detection in javascript, you can use it.
You can't do that directly using Javascript
<script>
tags. Media queries are used in linked CSS files or inline CSS styles. A basic example:Or directly in your stylesheets:
However, you can use an external asset loader/media query library to do this (require.js, modernizr.js, enquire.js and others), In this case, I'm setting an example using enquire.js, as I think it's very effective and doesn't require jQuery by default:
Full example
1) Include enquire.js (available here):
2) Create a load function - to load JS files:
3) Fire enquire.js and listen for media query changes (both on-load and on-resize):
Putting it all together
Using a simple HTML page with enquire.js loaded from an external file:
In addition to loading JS files, you could create a CSS loader too, which would work in the same way (conditionally), but that defeats the object of using
@media
in CSS. It's worth reading the usage explanations for enquire.js, as it can do a lot more than I've illustrated here.Caveat: Nothing above uses jQuery, but you could take advantage of some of the functions it offers; loading scripts for example - or executing other functions that you need to.