Detecting browser width with media query using jQuery - javascript

I am trying to implement a precise way of figuring out the user's browser width based on a media query. For example, I have an element div called #check_screen initially it'll be displayed as a block element. If the browser width is < 420px, then #check_screen will have a display: none property. This is what I have tried so far:
HTML
<div id='check_screen'></div>
CSS
#check_screen{
display: block;
}
#media only screen and (max-width: 420px){
#check_screen{
display: none;
}
}
jQuery
$(document).ready(function() {
// run test on initial page load
checkSize();
// run test on resize of the window
$(window).resize(checkSize);
});
//Function to the css rule
function checkSize(){
if ($("#check_screen").css("display") == "none" ){
console.log("hello");
}
}
For some reason, it is not working correctly. When I resize the screen to < 420px, the message is not displayed to the console. I have also tried using the :visible jQuery selector, but that does not work either. I am using Chrome as my browser.

I think you have a syntax error:
$(window).resize(checkSize); should be
$(window).resize(function(){
checkSize();
});
That correction worked for me with no other changes.

Assign unvisible div and set its color to black.
If resized, change its color to green.
Javascript would be like
var check = $("element").css("background-color");
if(check == "black" {
}
else if...

Related

Reload jquery script after resize display

I have a problem with jquery script if page size was changed. For example - if you open site on the phone, then open and close menu, then rotate phone from vertical to horizontal and open menu again - the block will not shown.
I use this script
return $(document).ready(function() {
(function($) {
if ($(window).width() < 960) {
$('#header-menu').css('display', 'none');
$('header.grid-container').css('display', 'none');
return $('#toggle-mobile-menu').click(function() {
$('#header-menu').toggle();
return $('header.grid-container').toggle();
});
}
})(jQuery);
});
I need some hook maybe, to reload script if screen was changed, without reload page. I tried to use $(window).resize() but it didn't work
It is impossible Jquery gets put into the DOM and would require a page refresh in order for the script to change.
You should consider using AJAX instead.
The problem is that your script is triggered only once after loading all DOM elements (Your are checking the screen width and if condition is done you are triggering the event). I suggest move styling to CSS (media queries) and use jquery only for binding events
CSS
#media (max-width: 960px) {
#header-menu,
.grid-container { display: none; }
#toggle-mobile-menu { display: block; } // or whatever
}
JS
$(function(){
$('#toggle-mobile-menu').on('click', function() {
$('#header-menu').toggle();
$('header.grid-container').toggle();
}
});

How does the CSS mediaQuery works

I need to know how the CSS media query works.
I mean, if I use #media(min-width: 768px), does this function called every time the window is resized ?
Because I am wondering if I can use a Javascript $(window).bind('resize orientationchange') or if it is more resource intensive.
It is for add or remove a class to a div, an exemple :
http://jsfiddle.net/xbh28o08/
My goal is to enter in the HTML a data attribut which determine when the navbar has to collapse (data-breakpoint"768" for example). And I would get this breakpoint for make a responsive navbar automatically, without change any CSS. My idea was to do it with Javascript but it seems really not a good idea according to your answers
var widthScreen = $(window).width();
if (widthScreen > 768)
$('nav').addClass('large');
else
$('nav').addClass('small');
$(window).bind('resize orientationchange', function() {
widthScreen = $(window).width();
if (widthScreen > 768){
$('nav').addClass('large');
$('nav').removeClass('small');
}
else{
$('nav').removeClass('large');
$('nav').addClass('small');
}
});
to answer your first question: yes a media query does get called every time you do resize the window.
there is no need to add classes with javascript, I provided you with an example:
it does completely the same but no js needed. Its better to avoid using javascript when its not needed.
nav{
background: green;
}
#media(min-width: 768px){
nav{
background: red;
}
}
<nav>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
</nav>
I suggest you use css media queries instead of javascript as css is faster than javascript
As soon as Your device width is 768px all the css in that will be called and would overwrite the any other if exist
For more info you can check the link below
Css Media Queries
A CSS media query will apply whenever the conditions in it are fulfilled (for instance, media screen and max-width of 768px), and be ignored whenever it is not. It applies to the window size and will update on resize. You can test this on this website by shrinking your browser.
Such a use-case (using the window resize event) is not recommended as it will trigger on every resize event. Not just when the resizing is finished, but also every tick between start and end. The only use case I know of is to add/remove classes, which is both not recommended, and also a downright CPU hog.
Media query will trigger only when particular point (width or height) mentioned in your media query, whereas javascript resize will trigger at every pixel changed during resize. And, JS is more resource intensive IMO whereas CSS is not and faster. Have a read here
So, in your case, instead of removing and adding classes, have one class and override it's properties based on the screen size in your media query. Something like:
.my-class { width: 400px; }
#media(min-width: 768px){
.my-class { width: 200px; }
}
OR
You can have 2 classes all the time, but only one will take effect based on the screen size. This way you don't override properties (which is a bit ugly, but, that's just me)
// screen <= 767
#media(max-width: 767px){
.nav-small {
width: 320px;
}
}
// screen >= 768
#media(min-width: 768px){
.nav-large {
width: 100%;
}
}

how to make mediaQuery over write values which were set dynamically in the code?

I have a div which has a basic width value, set in a css file.
In that file, i also have a media query for a new basic width, upon orientation change to portrait.
in my javaScript i have a function updating the width dynamically when document is ready.
What happens is, that when the media query is called, the updated width - is the width which was set dynamically by the js, and it's automatically overwrites the new media query css width.
In other words, once I dynamically set the width in the code - the media query will no longer take any effect.
how can i make the media query css width overwrite the current width (which was set dynamically by js?)
THANK YOU!
HTML + JS :
<html>
<head>
<script>
var defaultNumOfItem = 3;
$(document).ready(function()
{
updateWidth(4);
});
function updateWidth(currentNumOfItems) {
var basicWidthText = $('#list').css('width');
var basicWidth = parseFloat(basicWidthText .slice(0, basicWidthText .indexOf('px')));
$('#list').css('width', basicWidth * currentNumOfItems/ defaultNumOfItem);
}
$(window).bind('orientationchange, function(){
updateWidth(4);
});
</script>
</head>
<body>
<div id='list'>
</div>
</body>
</html>
CSS:
#list {
width: 900px;
}
#media only screen and (orientation: portrait){
#list {
width: 600px;
}
}
P.S the use of !important did not work for me, since if i put it in the css - the js will take no effect. and if i put it in the js - the media query takes no effect - same will happen by putting it in both the js and the css
This can probably be achieved without JavaScript, though the full intent of the code is not totally clear, so this is how to do it while maintaining the current functionality.
#media only screen and (orientation: portrait) {
#list {
max-width: 600px;
}
}
The max-width CSS property trumps width, even if width is defined inline, externally, or made !important. The same is true of the min-width property under different circumstances.
Just give it a try !important
#media only screen and (orientation: portrait){
#list {
width: 600px !important;
}
}
If I understand this correctly you want to use the media query only if orientation is portrait and the js if the orientation is landscape. In this case you can try this:
$(window).bind('orientationchange', function(event){
if(event.orientation != "portrait")
updateWidth(4);
});
this way the js will not overwrite the width that you wanted to set through the media query in portrait
Ok, found a work around that actually works!
What i do, is simply remove the "width" attribute from the #list every time the orientation changes:
$(window).bind('orientationchange, function(){
$('#list').css('width','');
updateWidth(4);
});
so that way, the external css does take before the js manipulation.

jQuery - If screen is less than specified width (responsive)

How can I make an alert popup if the width of the page is less than 1200px, and made responsive?
Thanks!
You can use something like the breakpoints module. Then you setup a breakpoint to trigger at 1200px and show a dialog and either add a css class that changes the layout, or use straight javascript to make the changes.
breakpoints(1200, function(oldPoint, newPoint) {
alert('The screen width just changed');
});
if you just wanted native jQuery:
$(window).resize(function() {
var width = $(window).width();
if (width < 1200){
alert('Your screen is too small');
}
});
For completeness, heres the CSS media query (still doesn't take care of the alert, but can help with making the website "responsive").
/* some normal style */
.myclass {
font-size: 22pt;
}
/* alter the style when the screen's smaller */
#media screen and (max-width: 1200px) {
.myclass {
font-size: 18pt;
}
}
For future Googlers, a 2019 solution is to use JavaScript's window​.match​Media(). It is supported in all major browsers and IE 10 onwards.
You can use it like this:
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
To make this responsive, you just need to wrap it in a resize function:
$(window).resize(function() {
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
});
This is arguably the most easiest way to check a screen size and it doesn't bloat the code.
Check the Mozilla docs about match​Media to learn more and this one for more info on Testing media queries programmatically.

How to hide a div if it overlaps another div

Is this CSS or javascript? I just need the div to change to display:none if it comes within say 20px of another div. Thanks
Try this
https://github.com/brandonaaron/jquery-overlaps
//Listen to the event that will be triggered on window resize:
window.onresize = function(event)
{
// test if one element overlaps another
if($('#div1').overlaps('#div2'))
{
//Do stuff, like hide one of the overlapping divs
$('#div1').hide();
}
}
Based on your comment:
Yes it is so that if the user makes their browser window small my site
does not look crowded
Instead of answering the question you asked, Here's an answer to the question you didn't ask:
How to resize/position/cssify page elements based on browser size?
There is a new-ish application of css and javascript called Responsive Web Design. Responsive Design allows you to specify different css rules to apply based on different elements. For a great example of this technique, resize your browser around on The Boston Globe's website. They just integrated this technique sometime this week.
Here's an example of the css that would implement this:
#media screen and (min-width: 480px) {
.content {
float: left;
}
.social_icons {
display: none
}
// and so on...
}
example from http://thinkvitamin.com/design/beginners-guide-to-responsive-web-design/
Here is a boilerplate to get you going.
You can add an event handler that gets fired when the window is resized. You could do this with javascript or jquery. jquery makes it easy:
window.onresize = function(event) {
var h=$(window).height();
var w=$(window).width();
if(h<400 && w < 300){
//hide divs
$('#yourdivid1').hide();
}
}
Hope this helps

Categories