Reputation: 4363
I was trying something with JavaScript and media queries. I want to change some elements with JavaScript, like switching elements etc.
When the browser/device width is 320px I want to do something.
I came up with the following, but this doesn't work:
if (screen.width < 320){
$('input[type="text"]').insertAfter('label');
$('input[type="text"]').eq(1).remove();
$('input[type="text"]').eq(2).remove();
}
What am I doing wrong?
When I would like to do this for some changes of my CSS it looks like this:
@media only screen and (max-width : 400px) { }
And the example above I want to convert to JavaScript.
Upvotes: 1
Views: 1039
Reputation: 1896
You can call media queries inside JavaScript:
function resize() {
if (window.matchMedia('only screen and (max-width: 400px)').matches) {
document.body.style.background = 'red';
} else if (window.matchMedia('only screen and (min-width: 401px) and ' +
'(max-width: 600px)').matches) {
document.body.style.background = 'blue';
} else {
document.body.style.background = 'yellow';
}
}
window.addEventListener('resize', resize, false);
resize();
Upvotes: 2
Reputation: 68586
Yes. You can do so by using $(window).width().
if ($(window).width() < 320) {
$('input[type="text"]').insertAfter('label');
$('input[type="text"]').eq(1).remove();
$('input[type="text"]').eq(2).remove();
}
Also, if you want to check if a resize has happened without refreshing, use $(window).resize().
Here's an example jsFiddle of resize in use.
Upvotes: 1
Reputation: 15609
Yes you can. Whilst media queries are great for css sometimes we need to load js based on the device size.
Media Match written by Paul Irish is a great tool to do this. It is used in Modernizr a feature detection library.
Upvotes: 0
Reputation: 914
Please refer below URL:
Phonegap - reliable page width detection?
You can use Navigator object to detect the devices in jquery.
Upvotes: 1