Why wont my navbar collapse when on mobile on page load - javascript

I'm trying to collapse the navbar when on mobile but the navbar only collapses when i resize the tab manualy. So it probably has something to do with it not checking the size of the screen when starting up the site. I've already tried some stuff with addeventlisteners but i just keep getting errors because op unexpected tokens. my original code was:
function openNav() {
document.getElementById("mySidebar").style.width = "190px";
document.getElementById("main").style.marginLeft = "190px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}
var x = window.matchMedia("(max-width: 600px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
function myFunction(x) {
if (x.matches) { // If media query matches
closeNav()
}
}
after asking some people for help i eventualy started to mess around with this:
var x = window.matchMedia("(max-width: 600px)")
x.addEventListener("change", () => {
myFunction(x);
});
and
window.addEventListener('resize', ()=>{
var x = window.matchMedia("(max-width: 600px)")
if (x.matches) { // If media query matches
closeNav()
}
});
I have been awake for hours and i know it's probably something stupid.

Instead of JavaScript you can use CSS #media-queries like:
#media only screen and (min-width:0px) and (max-width: 767px)
{
'your style here'
}
#media only screen and (min-width:768px) and (max-width: 1024px) and (orientation: portrait)
{
'for tablet portrait view'
}
#media only screen and (min-width:768px) and (max-width: 1024px) and (orientation: landscape)
{
'tablet view landscape'
}
Also please don't forget to add viewport meta tag in your page section.
meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=3"
(keep above meta tag inside < /> )
view port meta tag will read your browser resizing and you can achieve to response web layout, show and hide elements in specific device sizes etc.

Related

Multiple media queries in javascript

I'm trying to check the screen size with Javascript.
My elements will be animated differently depending on the size of the screen.
I think I am not too far from the result but without really fully understanding it.
When I load the page I have a console.log that appears twice regardless of the size of the window.
By reducing the window manually, by dragging the mouse, there is:
- 2 console.log('MD') when the size for MD is ok
- 1 console.log('SM') when the size for SM is ok
By enlarging the window manually, by dragging the mouse, there is:
- 1 console.log('MD') when the size for MD is ok
- 1 console.log('SM') when the size for LG is ok
- 1 console.log('LG') when the size for LG is ok
But by adjusting the size of the window with the browser icon, my console.log are as I wish.
Would it be possible to have more explanation?
I hope I've made myself clear.
let mqls = [
window.matchMedia('screen and (min-width: 768px) and (max-width: 991px'),
window.matchMedia('screen and (min-width: 992px)')
];
function test(mql){
if( mqls[0].matches ){
console.log('MD')
}
else if( mqls[1].matches ){
console.log('LG')
}
else if( !mqls[0].matches && !mqls[1].matches ){
console.log('SM')
}
}
for ( let i =0; i < mqls.length; i++ ){
test(mqls[i]);
mqls[i].addListener(test);
}
function checkScreen(){
const checkMobile = window.matchMedia('screen and (max-width: 575px)');
const checkTablet = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
const checkDesktop = window.matchMedia('screen and (min-width: 992px)');
checkMobile.addListener(function(e){
if(e.matches) {
console.log('MOBILE');
}
});
checkTablet.addListener(function(e){
if(e.matches) {
console.log('TABLET');
}
});
checkDesktop.addListener(function(e){
if(e.matches) {
console.log('DESKTOP');
}
});
}
checkScreen()
I figure it out but maybe there is better solution ?
EDITED
with the solution above my function doesn't start when my page loads or when refreshing so I have to do this
mobile();
function mobile(){
const mql = window.matchMedia('screen and (max-width: 575px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('Mobile');
}
}
}
tablet();
function tablet(){
const mql = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('tablet');
}
}
}
desktop();
function desktop(){
const mql = window.matchMedia('screen and (min-width: 992px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('desktop');
}
}
}
If I put my media queries in an array and use a loop at each refresh as much output in my console as item in my array
There's probably something I don't understand.

Is there a more efficient way of adding and removing these CSS classes with jQuery?

I have the below script that uses slidebars to show and hide a side menu.
I need to add and remove a CSS class to another div to tie things together. But looking at the way I am adding and removing classes I feel like there's a more efficient way?
function slidebarsStatus() {
var windowWidth = $(window).width();
breakpoint = 992;
if ( windowWidth > breakpoint ) {
controller.open( 'site-menu' );
$('.site-wrap').addClass('menu-active');
}
else {
controller.close( 'site-menu' );
$('.site-wrap').removeClass('menu-active');
$('.site-wrap').addClass('menu-inactive');
}
}
slidebarsStatus();
$(window).on( 'resize', slidebarsStatus );
Store the jQuery object as a variable:
var siteWrap = $('.site-wrap');
And chain your methods to the variable:
siteWrap.removeClass('menu-active').addClass('menu-inactive');
Or, if possible, media queries in your CSS:
#media screen and (max-width: 991px) {
.site-wrap {
/* active appearance */
}
}
#media screen and (min-width: 992px) {
.site-wrap {
/* inactive appearance */
}
}

Detect dynamic media queries with JavaScript without hardcoding the breakpoint widths in the script?

I've been searching for a lightweight, flexible, cross-browser solution for accessing CSS Media Queries in JavaScript, without the CSS breakpoints being repeated in the JavaScript code.
CSS-tricks posted a CSS3 animations-based solution, which seemed to nail it, however it recommends using Enquire.js instead.
Enquire.js seems to still require the Media Query sizes to be hardcoded in the script, e.g.
enquire.register("screen and (max-width:45em)", { // do stuff }
The Problem
All solutions so far for accessing Media Queries in Javascript seem to rely on the breakpoint being hardcoded in the script. How can a breakpoint be accessed in a way that allows it to be defined only in CSS, without relying on .on('resize')?
Attempted solution
I've made my own version that works in IE9+, using a hidden element that uses the :content property to add whatever I want when a Query fires (same starting point as ZeroSixThree's solution):
HTML
<body>
<p>Page content</p>
<span id="mobile-test"></span>
</body>
CSS
#mobile-test {
display:none;
content: 'mq-small';
}
#media screen only and (min-width: 25em) {
#mobile-test {
content: 'mq-medium';
}
}
#media screen only and (min-width: 40em) {
#mobile-test {
content: 'mq-large';
}
}
JavaScript using jQuery
// Allow resizing to be assessed only after a delay, to avoid constant firing on resize.
var resize;
window.onresize = function() {
clearTimeout(resize);
// Call 'onResize' function after a set delay
resize = setTimeout(detectMediaQuery, 100);
};
// Collect the value of the 'content' property as a string, stripping the quotation marks
function detectMediaQuery() {
return $('#mobile-test').css('content').replace(/"/g, '');
}
// Finally, use the function to detect the current media query, irrespective of it's breakpoint value
$(window).on('resize load', function() {
if (detectMediaQuery() === 'mq-small') {
// Do stuff for small screens etc
}
});
This way, the Media Query's breakpoint is handled entirely with CSS. No need to update the script if you change your breakpoints. How can this be done?
try this
const mq = window.matchMedia( "(min-width: 500px)" );
The matches property returns true or false depending on the query result, e.g.
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
You can also add an event listener which fires when a change is detected:
// media query event handler
if (matchMedia) {
const mq = window.matchMedia("(min-width: 500px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
}
See this post from expert David Walsh Device State Detection with CSS Media Queries and JavaScript:
CSS
.state-indicator {
position: absolute;
top: -999em;
left: -999em;
}
.state-indicator:before { content: 'desktop'; }
/* small desktop */
#media all and (max-width: 1200px) {
.state-indicator:before { content: 'small-desktop'; }
}
/* tablet */
#media all and (max-width: 1024px) {
.state-indicator:before { content: 'tablet'; }
}
/* mobile phone */
#media all and (max-width: 768px) {
.state-indicator:before { content: 'mobile'; }
}
JS
var state = window.getComputedStyle(
document.querySelector('.state-indicator'), ':before'
).getPropertyValue('content')
Also, this is a clever solution from the javascript guru Nicholas C. Zakas:
// Test a media query.
// Example: if (isMedia("screen and (max-width:800px)"){}
// Copyright 2011 Nicholas C. Zakas. All rights reserved.
// Licensed under BSD License.
var isMedia = (function () {
var div;
return function (query) {
//if the <div> doesn't exist, create it and make sure it's hidden
if (!div) {
div = document.createElement("div");
div.id = "ncz1";
div.style.cssText = "position:absolute;top:-1000px";
document.body.insertBefore(div, document.body.firstChild);
}
div.innerHTML = "_<style media=\"" + query + "\"> #ncz1 { width: 1px; }</style>";
div.removeChild(div.firstChild);
return div.offsetWidth == 1;
};
})();
I managed to get the breakpoint values by creating width rules for invisible elements.
HTML:
<div class="secret-media-breakpoints">
<span class="xs"></span>
<span class="tiny"></span>
<span class="sm"></span>
<span class="md"></span>
<span class="lg"></span>
<span class="xl"></span>
</div>
CSS:
$grid-breakpoints: (
xs: 0,
tiny: 366px,
sm: 576px,
md: 768px,
lg: 992px,
xl: 1200px
);
.secret-media-breakpoints {
display: none;
#each $break, $value in $grid-breakpoints {
.#{$break} {
width: $value;
}
}
}
JavaScript:
app.breakpoints = {};
$('.secret-media-breakpoints').children().each((index, item) => {
app.breakpoints[item.className] = $(item).css('width');
});
I found an hackish but easy solution :
#media (min-width: 800px) {
.myClass{
transition-property: customNS-myProp;
}
this css property is just a markup to be able to know in JS if the breaking point was reached. According to the specs, transition-property can contain anything and is supported by IE (see https://developer.mozilla.org/en-US/docs/Web/CSS/transition-property and https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident).
Then just check in js if transition-property has the value. For instance with JQuery in TS :
const elements: JQuery= $( ".myClass" );
$.each( elements, function (index, element) {
const $element = $( element );
const transition = $element.css( "transition-property" );
if (transition == "custNS-myProp") {
// handling ...
}
});
Of course there is a word of warning in the wiki that the domain of css property identifiers is evolving but I guess if you prefix the value (for instance here with customNS), you can avoid clashes for good.
In the future, when IE supports them, use custom properties instead of transition-property
https://developer.mozilla.org/en-US/docs/Web/CSS/--*.

apply classname (css) based on screen resolution

I have a problem when I am working on resolution base application.
If I have 1024 by 768 resolution my application should be 100% (table Layout). If I have above 1024 by 768 resolution the application should be in center align (table width is 80%).
function MOSTRA() {
var SCR = screen.availWidth;
var BRW = window.outerWidth;
if (BRW < SCR) {
document.getElementById('sample').className = 'maintable';
} else {
document.getElementById('sample').className = 'maintable1';
}
}
window.onresize = MOSTRA;
window.onload = MOSTRA;
I have used the above code but this is not working.
Hi all i have checked with putting alert in required place. Now i know where the problem is occurring in window.outerWidth it seems because when i alert in that area i am getting undefined in IE. It seems Ie is not supporting outerwidth. I have taken the above code from the below link.
http://jsfiddle.net/Guffa/q56WM/
Please helpe me.
This is a urgent issue
Thanks in advance
Use CSS3 Media Queries:
#media screen and (min-width: 1024px) and (min-width: 768px)
{
/* Center table! */
}
Also possible:
<link rel="stylesheet" media="screen and (min-width: 1024px) and (min-width: 768px)" href="example.css" />
JS variant (because OP didn't want CSS 3):
if (window.screen.width >= 1024 && window.screen.width >= 768) {
document.head.innerHTML += '<link rel="stylesheet" href="centerTable.css" type="text/css" />'
}
Pragmatically include style-sheets based on display width, media type: http://www.w3.org/TR/css3-mediaqueries/

CSS media queries and jQuery window .width() do not match

For a responsive template, I have a media query in my CSS:
#media screen and (max-width: 960px) {
body{
/* something */
background: red;
}
}
And, I made a jQuery function on resize to log the width:
$(window).resize( function() {
console.log( $(window).width() );
console.log( $(document).width() ); /* same result */
/* something for my js navigation */
}
And there a difference with CSS detection and JS result, I have this meta:
<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" name="viewport"/>
I suppose it's due to the scrollbar (15 px). How can I do this better?
You're correct about the scroll bar, it's because the CSS is using the device width, but the JS is using the document width.
What you need to do is measure the viewport width in your JS code instead of using the jQuery width function.
This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
I found following code on http://www.w3schools.com/js/js_window.asp:
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Practically its working the same way as the answer in #Michael Bird's answer, but it's more easy to read.
Edit: I was looking for a method to give exactly the same width as it is used for css media queries. But the suggested one does not work perfect on Safari with scrollbars, sorry. I ended up using modernizr.js in one central function and in the rest of the code I just check if display type is mobile, tablet or desktop. As I am not interested in the width, this works fine for me:
getDisplayType = function () {
if (Modernizr.mq('(min-width: 768px)')){
return 'desktop';
}
else if (Modernizr.mq('(min-width: 480px)')){
return 'tablet'
}
return 'mobile';
};
window.innerWidth is what you need.
if (window.innerWidth < 768) works for 768 break point in CSS
Workaround that always works and is synced with CSS media queries.
Add a div to body
<body>
...
<div class='check-media'></div>
...
</body>
Add style and change them by entering into specific media query
.check-media{
display:none;
width:0;
}
#media screen and (max-width: 768px) {
.check-media{
width:768px;
}
...
}
Then in JS check style that you are changing by entering into media query
if($('.check-media').width() == 768){
console.log('You are in (max-width: 768px)');
}else{
console.log('You are out of (max-width: 768px)');
}
So generally you can check any style that is being changed by entering into specific media query.
My experience was that the media query width tracks document.body.clientWidth. Because of a vertical scroll bar coming and going, checking document, window, or viewport().width could cause my Javascript to run late--after the media query rule change, depending on the height of the window.
Checking document.body.clientWidth allowed my script code to execute consistently at the same time the media query rule took effect.
#media (min-width:873px) {
//some rules
}
...
if ( document.body.clientWidth >= 873) {
// some code
}
The Andy Langton code put me onto this--thanks!
Hi i use this little trick to get JS and CSS work together easily on responsive pages :
Test the visibility of an element displayed or not on CSS #media size condition.
Using bootstrap CSS i test visibility of a hidden-xs class element
var msg = "a message for U";
/* At window load check initial size */
if ( $('#test-xsmall').is(':hidden') ) {
/* This is a CSS Xsmall situation ! */
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
/* > 768px according to CSS */
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
/* And again when window resize */
$(window).on('resize', function() {
if ($('#test-xsmall').is(':hidden')) {
msg = "#media CSS < 768px. JS width = " + $(window).width() + " red ! ";
$('.redthing-on-xsmall').addClass('redthing').html(msg);
} else {
msg = "#media CSS > 767px. JS width = " + $(window).width() + " not red ! ";
$('.redthing-on-xsmall').removeClass('redthing').html(msg);
}
});
#media (min-width: 768px) {
.hidden-xs {
display: block !important;
}
}
#media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
.redthing-on-xsmall {
/* need a scrollbar to show window width diff between JS and css */
min-height: 1500px;
}
.redthing {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- the CSS managed Element that is tested by JS -->
<!-- class hidden-xs hides on xsmall screens (bootstrap) -->
<span id="test-xsmall" class="hidden-xs">THIS ELEMENT IS MANAGED BY CSS HIDDEN on #media lower than 767px</span>
<!-- the responsive element managed by Jquery -->
<div class="redthing-on-xsmall">THIS ELEMENT IS MANAGED BY JQUERY RED on #media max width 767px </div>
Css media query is equal to window.innerWidth. Css Media Queries calculate the scrollbar as well.
The simple and reliable way of doing this is to use Media Queries.
To demonstrate, I want to check if the screen width is greater than or equal to 992px (Bootstrap's large device):
function isLargeDevice() {
if (window.matchMedia("(min-width: 992px)").matches) {
return true;
}
return false;
}
If you are using Modernizer then it's a bit easier, here I want to check if the screen is smaller than Bootstrap's large screen (992px)
function isSmallerThanLargeScreen() {
if (Modernizr.mq('(max-width: 991px)')) {
return true;
}
return false;
}

Categories

Resources