Issue changing javascript function based on media query with event handler - javascript

Sorry if this is a basic question. I mainly work with design and am not entirely comfortable with JavaScript.
I have a navigation menu which is prompted to display when clicking an SVG using an Event Listener. Based on the size of the screen on which the menu is being displayed I would like to change the function to a function stating a different height for the navigation on click. This way smaller devices will have a certain height navigation, and larger will have a different height as well.
Here is the code as far as I have dabbled into it
// 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) {
// at least 500px
document.getElementById("onclick").addEventListener("click", menuSize);
function menuSize() {
document.getElementById("mobilemenu").style.height = "35%";
document.getElementById("mobilemenu").style.opacity = "1";
document.getElementById("movbilenav").style.opacity = "0";
}
} else {
// less than 500px
document.getElementById("onclick").addEventListener("click", menusizeL);
function menusizeL() {
document.getElementById("mobilemenu").style.height = "50%";
document.getElementById("mobilemenu").style.opacity = "1";
document.getElementById("movbilenav").style.opacity = "0";
}
}
}
As of now I get no response at all when clicking the navigation menu. Thank you, and sorry if this is a rudimentary question.

I think you should convert your solution to mainly use css. Generally, the more you can solve with css instead of js, the more the browser will take care of everything and keep everything smooth.
You can just add a media query in your stylesheets to handle the height differences. To hide/show your menu, I'd rely on just adding a class via your js. Sample stylesheet:
#mobilemenu {
height: 50%;
opacity: 0;
}
#mobilmenu.showing {
opacity: 1;
}
#media (min-width: 500px) {
#mobilemenu {
height: 35%;
}
}
Then you can just add your class via js:
document.getElementById('menuopener').addEventListener('click', function() {
document.getElementById('mobilemenu').classList.toggle('showing');
});

Related

JS match.Media with media query range

I am having an issue getting my site to respond to matchMedia query range using media.Match.
Updates based on comments: I need to use match.Media instead of CSS media queries because i need to check if a component is present and if true, i then need to add a class to another element if the browser size is between 1400 - 1800px. Also, i do need this to fire every time the browser is resized.
To troubleshoot, I have tried:
Using a single matchMedia('(min-width: 1400px) and (max-width: 1800px)')
Doing a single match (using only min-width: 1400px) and that succeeds. However, when I add in my 2nd variable 'mq.Max' and 'and statement', the whole thing fails.
I have read through MDN and still not seeing how to implement this.
JS below, thank you for any suggestions you may have.
if (jQuery('.jump-nav').length) {
// Create a condition that targets viewports at least 770px wide
window.onresize = function (event) {
console.log(event);
var mqMin = window.matchMedia('(min-width: 1400px)');
var mqMax = window.matchMedia('(max-width: 1800px)');
// check if media query matches#media (min-width: 30em) and (orientation: landscape)
if (mqMin.matches && mqMax.matches) {
console.log('Media Query Matched!')
// add css class for desktop
$('.rowComponent').addClass('jn-rowchange');
} else {
// remove css class if not desktop
$('.rowComponent').removeClass('jn-rowchange');
}
};
}
This is something that worked for me!
let mqMin = window.matchMedia("(min-width: 768px)");
let mqMax = window.matchMedia("(max-width: 960px)");
window.onresize = function () {
if (mqMin.matches && mqMax.matches) {
console.log("Inside Query parametara!");
} else {
console.log("Outside Query parametara!");
}
};

How to refresh a variable upon resizing the browser using Vanilla JavaScript?

I grab the size of a slide image using let size = carousel_images[0].clientWidth; and clientWidth varies in different viewports, here, carousel_images is pointing to img within the .carousel and here is how it varies in different viewports:
#media screen and (min-width: 1024px) {
.carousel {
max-width: 994px;
img {
min-width: 994px;
}
}
}
#media screen and (min-width: 1200px) {
.carousel {
max-width: 1150px;
img {
min-width: 1150px;
}
}
}
so when I resize the browser it looks like:
but as I refresh the page, it looks normal again.
here is full code pen link, Thank You.
You need to add this code:
window.addEventListener('resize', ()=>{
size = carousel_images[0].clientWidth
carousel_slide.style.transform = `translateX(${-size}px)`
})
Essentially, you need to listen window resize event, update variable and execute code again wherever that variable is used.
I think you have to assign a new value to your let size. Is it a global variable? Perhaps, putting it inside a function or class is a good idea.
You could use the resize event, which fires when your window changes size.
The following demo is from:
https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');
function reportWindowSize() {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
}
window.onresize = reportWindowSize;
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>

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/--*.

JS "#media" device resolution change property of js command

I'm doing responsivity on my website in JS. How can I change this (normal resolution):
$(".card1_content_arrow").click(function () {
$(".card1_content").css('margin-left', '-45%');
});
Into this, when media width is <860px (in css #media all and (max-width: 860px)):
$(".card1_content_arrow").click(function () {
$(".card1_content").css('margin-left', '-100%');
});
When I click on .card1_content_arrow on big resolution, then margin-left will be changed to -45%', but if I will change the resolution to 860px (and less) I want, that when I click on same .card1_content_arrow, then margin-left will be changed to -100%.
Thanks :)
You can detect the screen resolution as described on this question.
$(".card1_content_arrow").click(function () {
var margin = "-45%";
if (window.screen.availWidth < 860) {
margin = "-100%";
}
$(".card1_content").css('margin-left', margin);
});
I would suggest using media queries instead by specifying another class to control the margin.
.yourClass {
margin-left: -45%;
}
#media (max-width: 859px) {
.yourClass {
margin-left: -100%;
}
}
You can just add the class into your element and let the browser do the checking.
$(".card1_content_arrow").click(function () {
$(".card1_content").addClass('yourClass');
});

Retrieving first value of css property after changing by jquery or javascript

Suppose that there is a div element and we are in 760px width. Current margin-top as css property value will be 60px.
CSS:
#media only screen and (min-width: 360px) {
div.me {
margin-top: 30px;
}
}
#media only screen and (min-width: 760px) {
div.me {
margin-top: 60px;
}
}
Then I change the margin-top by jquery to do more stuff. e.g. 80px.
Jquery
$("div.me").css("margin-top", "80px");
I'm searching a solution for: When the user resized the window, Doing reset the element margin-top to first documnet ready value depend on it's media query.
Suppose the user resized to 400px width. So the element should be reset to margin-top: 30px.
I thought to set custom attributes to all elements to save first values in it.
$(document).ready(function () {
var m = $("div.me").css("margin-top");
$("div.me").attr("first-margin-top", m);
});
$(window).resize(function () {
// some stuff to retrieve first value, not important...
});
But There are many elements like this on the page and many media query values for each.. Here I just talked about one element.
Is there a better way to retrieve and reset the element? Any idea?
You set the CSS value inline therefore it trumps your media query. Either do this with jquery or add the !important tag into your css:
#media only screen and (min-width: 760px) {
div.me {
margin-top: 60px !important;
}
}
$(window).resize(function () {
if($(window).width < 760){
$("div.me").css("margin-top", "60px");
}
});
Finally I found the answer of my own question. I just changed inline style to "" or removed it. It makes the browser to set margin-top or other properties (if needed) according to media query values again.
$(window).resize(function () {
$("div.me").css("margin-top", "");
//or
$("div.me").removeAttr("style");
});
JsFiddle

Categories

Resources