Using template in angular 2 based on window size - javascript

On my template, I have 2 divs. one for table view(laptop) and one for list view(mobile view).
In my .ts file, I want to get the window size so that based on this size, I can choose which div i want to call using ngIf.
In the constructor of the .ts file, I have:
let windowSize: number;
this.windowSize = innerWidth + innerHeight;
window.addEventListener("resize", function() {
this.windowSize = innerWidth + innerHeight";
});
But when i console.log() this.windowSize, I dont get the change when the window is resized. What am i missing?

This can be set with simple css:
#media (min-width: 500px) and (max-width: 700px) {
.div1 {
display: none;
}
#media (min-width: 701px) and (max-width: 900px) {
.div2 {
display: none;
}

Resolved this issue by using NgZone. Injected NgZone in my constructor and used it as:
window.onresize = (e) =>
{
this.ngZone.run(() => {
this.width = window.innerWidth;
this.height = window.innerHeight;
});
};
By doing this, I was able to check for the change in window in my components. I couldnt use media queries since I had to execute a funtion inside my .ts file based on window size change.

Related

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>

How to add css styles with JavaScript depending on the size of the browser

I am working with a Bootstrap 3 template and built a little JavaScript app. I am wanting to add a certain amount of margin to an element in one of the phases I created based on how big the viewport is. I have some code that I'm trying to work with but I keep getting the message Uncaught TypeError: Cannot read property 'matches' of undefined at MediaQueryList.myFunction. I cannot figure out why because all my variables that I am passing into the function as a parameter have values. I can see that the first value works because 17em is being applied but the value isn't changing when the size of the window changes. Disclaimer: I am fairly new to Javascript.
var x = window.matchMedia("screen and (min-width: 1200px)"),
y = window.matchMedia("screen and (min-width: 992px)"),
z = window.matchMedia("screen and (min-width: 768px)");
function myFunction(x, y, z) {
if (x.matches && phase === phases.crustType) {
doughSpan.style.marginLeft = "17em";
} else if (y.matches && phase === phases.crustType) {
doughSpan.style.marginLeft = "13em";
} else if (z.matches && phase === phases.crustType) {
doughSpan.style.marginLeft = "12em";
} else {
doughSpan.style.marginLeft = "0em";
}
}
myFunction(x, y, z);
x.addListener(myFunction);
y.addListener(myFunction);
z.addListener(myFunction);
I'd handle this via media queries. It's what they are designed for.
Set a class on doughSpan based on the phase. You'd do this where you're setting phase. Let javascript handle the manipulation of the DOM and leave the styling of it to CSS.
Something along the lines of the following
/*JS*/
function setPhase(phase) {
//Add the class "paseCrustType" to doughSpan if that is the active phase
doughSpan.classList.togggle("phaseCrustType", phase === phases.crustType);
}
/*CSS*/
.phaseCrustType {
margin-left: 0;
}
#media screen and (min-width: 1200px) {
.phaseCrustType {
margin-left: 17em;
}
}
#media screen and (min-width: 992px) {
.phaseCrustType {
margin-left: 13em;
}
}
#media screen and (min-width: 768px) {
.phaseCrustType {
margin-left: 17em;
}
}
When you call: x.addListener(myFunction), myFunction is only being passed the MediaQueryListEvent for x when it expects all three. You should generalize the function to accept a single MediaQueryListEvent and a margin to apply, and call addListener for each of your media queries.
Here's an example:
var x = window.matchMedia("screen and (min-width: 1200px)");
// declare y and z
var handleQuery = function(e, margin) {
if (e.matches && phase === phases.crustType) {
doughSpan.style.marginLeft = margin;
}
};
handleQuery(x, "17em");
// call handleQuery for y and z, passing along their margins
x.addListener(function(e) {
handleQuery(e, "17em");
});
// call addListener for y and z and handle them as you need
Check out the MediaQueryList.addListener docs for more details.

Adding #media Rule by Javascript

I am adding a dynamically created image using JavaScript, but I need to remove this object when the viewport is 600px or wider.
Here is what I've tried:
var img = document.createElement('img');
// (imagine here all the others fields being defined).
img.style='My #media Rule here';
However, it did not work. Is it possible doing this by the way I am trying to do?
Just create CSS class and apply it when image is dynamically added:
JavaScript:
var img = document.createElement('img');
img.className = "imageClass";
img.src = "image/src/image.jpg";
And stylesheet:
#media screen and (min-width: 600px) {
.imageClass {
display: none;
}
}
Example: https://jsfiddle.net/cr29y1tc/1/

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');
});

Categories

Resources