Reputation: 21
Simple question - Is it possible to use jquery with media queries so the jquery only happens below a certain screen size.
I have a navigation that uses hover on the desktop but I need to use click on mobile.
I have few other actions I want to control on mobile like preventDefault() actions on buttons
Upvotes: 2
Views: 515
Reputation: 737
@Mohamad Shiralizadeh
This is looking nice. However its only triggering on window resize. When you first load the page it doesn't trigger. So based on your example:
jQuery(document).ready(function ($) {
// do things when the document is ready
contentChanger();
// do things when the widow resizes
$(window).resize(function () {
contentChanger();
});
// change content based on viewport
function contentChanger() {
// viewport is 320 pixels or smaller
if ($(window).width() <= 320) {
// do things here
}
// viewport is 375 pixels or smaller but bigger than 320 pixels
if ($(window).width() <= 375 && $(window).width() > 320) {
// do things here
}
};
});
Upvotes: 1
Reputation: 11
Resizing the window is not very good.
The best approach is by using matchmedia
var mql = window.matchMedia("screen and (min-width: 800px)")
if (mql.matches){ // if media query matches
alert("Window is 800px or wider")
}
else{
// do something else
}
P.S. make sure you downloaded Typescript
Upvotes: 1
Reputation: 8765
you can do it in resize function of the windows:
$(window).on('resize', function (e) {
var width = $(window).width();
if (width > 1024)
// Codes
});
Upvotes: 0