Multiple scripts for responsive layout with (window).resize - javascript

So I am currently working on a one page site with a responsive layout. On smaller screens I am using an animated scroll plugin to navigate between the content divs, but on larger screens I am using a plugin to simply toggle the visibility of these divs.
The issue that I am having is that I need the script to change if the window is resized after the page has been loaded. I thought that $(window).resize would do the trick but it doesn't seem to be working and continues to use the script that was initially loaded rather than executing the proper script. .anchorAnimate and .anchorTog are the plugins that I am using but I do not think that they are the problem here. I can post if necessary.
Code:
$(document).ready(function() {
var w = $(window).width();
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
$(window).resize(function(){
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
});
});

in your code, the variable "w" is out of scope for the resize function. "w" will only ever be the window width when the document has reached it's ready state. To fix this, you can redeclare the variable in your resize function so that every time we get a resize, we check the width:
$(window).resize(function(){
var w = $(window).width();
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
});

Responsive design usually implies CSS, not JavaScript.
In CSS3 you can define the dimensions of the screen-size you want to support using #media.
If you use CSS you can have hardware accelerated animations, which are much smoother than anything you could do in JavaScript.
Google for "responsive design css3" and you'll get many examples.

Related

Change href depending on viewport size (without jquery)

I want to be able to change a href depending upon window width: on initial page load and window resize (without jquery or other external libraries).
Thank you!
Here is an experiment using an answer to a similar question: doesn't seem to be working for me. https://codepen.io/marcusdeacey/pen/wLLNXb
HTML
<a id="myLink" href="http://highresolutionurl">My Link</a>
JS
if (screen.width < 768) {
document.getElementById('myLink').setAttribute('href', "http://highresolutionurl");
}
else if {
document.getElementById('myLink').setAttribute('href', "http://lowresolutionurl");
}
screen.width doesn't change unless you change the display settings on your computer or mobile device. If you want this link to change dynamically with the width of the window, you need either window.innerWidth or window.outerWidth.
If you want this to change dynamically, you can't just do it once, you need to monitor changes in window size.
var myLink = document.getElementById('myLink');
function setLink() {
if (window.innerWidth < 768) {
myLink.setAttribute('href', "http://highresolutionurl");
}
else {
myLink.setAttribute('href', "http://lowresolutionurl");
}
}
setLink();
window.addEventListener('resize', setLink);
There's a JavaScript variable called screen.width which is pretty self explanatory, it gets the screens width. So for example:
if (screen.height > screen.width) {
//This means your on a mobile device so if you wanted people on mobile to go to mobile support instead of desktop support you could use this method
}
else {
//do something
}
//or you could just
if (screen.width == 1360) {
//Do this for people with only 1360 pixel wide screens
}
else {
//Do this for people without 1360 pixel screens
}

iOS 8 glitch effecting window resize

I've got some very simple code:
$(function() {
$(window).resize(function () {
if ($(window).width() < 500) {
$("#foo").show(); $("#foo2").hide();
} else if ($(window).width() > 501) {
$("#foo2").show(); $("#foo").hide();
}
}).resize();
});
All was working fine on desktop (all major browsers) and mobile (as many as I could test), till iOS 8 came out. Now when a users scrolls in Safari the javascript falls back to 'else if', creating 'foo2' and hiding 'foo' despite the browser not resizing. This is for a menu, as such the menu closes if the user scrolls which shouldn't be happening.
If I remove the window resize function all works as it should, however the menu doesn't update in real time if the user resizes the browser window.
Is there an alternative to window resize I can use to achieve the same effect?
...so, considering I get the problem as you describe it, you can avoid javascript and do it using pure css and media queries:
#media (max-width:500px) {
#foo {
display:block;
}
#foo2 {
display:none;
}
}
#media (min-width:501px) {
#foo2 {
display:block;
}
#foo {
display:none;
}
}
edit: ..this will definately have nothing to do with scrolling and will certainly be faster and cleaner
This might be a little late, but I'd store the width of the window on load and then check against that on the resize to ensure an actual resize took place horizontally. That would ensure that the code only fired when the browser changed size on the x axis.
var windowWidth = $(window).width();
$(window).resize(function(){
if (windowWidth !== $(window).width())
{
windowWidth = $(window).width();
// rest of your code goes here
}
});
Remember that the resize event could fire quite a lot while someone is resizing, so you may want to limit the whole thing using setInterval, but that's a separate discussion.

disabling javascript plugin based on window size

I'm coding a website essentially for three different breakpoints (desktop, tablet, mobile). I have a javascript plugin running an automatic image change for my full width background. As I resize my window to the tablet and mobile breakpoints, can I disable the javascript plug in and make it stop running when the window is smaller than ***px?
var minWidth = 800 // minimum width of screen
if ($(window).width() <= minSize) {
// do nothing
}
else {
// continue script
}
If you wanted it to be width as well as height:
if ($(window).width() <= minWidth && $(window).height() <= minHeight) {
Or something similar.

Call or Uncall function after resize or orientation changee

I'm working on a mobile web project that goes between a two column or single column view based on screen size. For some device sizes, changing from portrait to landscape switches you between the single and double column. Across the bottom of the page there are three feature images that are side by side for two column view, but we want to turn into a content slider in single column.
My issue:
The javascript conditional I have calls the function when the width of the screen is below a certain width. However if you change the orientation/size of the screen, it doesn't recall the function or re-evaluate the screen width.
What I have:
if( $(window).width() < 570) {
$(window).load(function() {
$('.flexslider').flexslider();
});
}
What is the best way to watch for resize and call/recall the function after the resize event?
Use jQuery resize event on window. jsfiddle
$(window).resize(function(){
//your code
});
To follow on from what Shusl said, you need to create the functions within $(window).resize();
What I would do is create the function and be sure to trigger it too. So it would be something like -
$(window)resize(function() {
winWidth = $(window).width();
winHeight = $(window).height();
if (winWidth < 570) {
$(window).load(function() { $('.flexslider').flexslider(); });
}
else {
// do something else
}
}).trigger("resize");

How do I increase the font size based on the window width?

I am creating a web-based app that will be displayed on television and other large monitors. I am wanting a quick and easy way to increase the font size to fit the window size. The text is dynamic.
Any help is greatly appreciated. ;)
If you're interested in / able to use CSS3 then there is a pure CSS solution - media queries >> http://www.w3.org/TR/css3-mediaqueries/
So for example, the CSS:
#media screen and (min-device-width: 800px) { ... }
...allows you to specify different styles for the page when displayed on a 800px screen or greater. Obviously you can vary this as you like - powerful stuff
You may also want to consider the prewritten javascript at the end of this link ...
http://www.themaninblue.com/experiment/ResolutionLayout/#
OK - for starters, you should use Ems for as many measurements as you can in your UI. At the very least, size all of your text elements with Ems (rather than pixels or %'s). If possible, setting the width of layout blocks in Ems will help the app scale in proportion, too. If you can set all your dimensions in Ems, your entire app will be visually scalable.
The key to Ems is that they're sized relative to the font size of their parent element - which means you can adjust the size of all the text in proportion, by adjusting the font-size of the body element (since everything is relative to the body).
The last step is to use a piece of javascript to detect the width of the viewport, and set the font-size of the body accordingly. Depending on how fine-grained you want to control the scale, you can either use classes on the body element to set up a set of pre-defined values, or directly manipulate the font-size itself. I'd tend to use pre-determined sizes if possible to make testing easier.
I'd use a javascript library to make the detection of the viewport width easier - it's notoriously different in different browsers. With jQuery, the code could look like:
$(function(){
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) {$('body').addClass('extraWide')}
else if (viewPortWidth > 1400) {$('body').addClass('wide')}
else if (viewPortWidth > 1000) {$('body').addClass('standard')}
else if (viewPortWidth > 700) {$('body').addClass('narrow')}
else {$('body').addClass('extraNarrow')}
});
And the CSS:
<style type="text/css">
body {font-size:62.5%;} /* Set the size of 1em to 10px in all browsers */
body.extraWide {font-size:85%;}
body.wide {font-size:75%;}
body.narrow {font-size:50%;}
body.extraNarrow {font-size:40%;}
</style>
Those values can be tweaked however you like, of course, and you can set up as many divisions as you want. This is very much a quick-and-dirty solution, but should do the trick.
A note - the javascript code shown will only set the scale once when the page is loaded - it won't adjust it when you change the size of your window. That's a possible addition, but there are bigger considerations before heading down that track. Personally, I'd even think about setting the scale value in a cookie, to keep the user's experience consistent throughout their session, rather than rescaling on every page load.
I know this in quite an old question, but I will be answering anyways due to this being a question that could be searched upon a lot.
There is actually another approach other than Media Queries which is also pure CSS:
Viewport units: vw, vh, vmin, vmax.
These are length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).
So for example you could use:
CSS:
body {
font-size:5vmin;
}
This sets the font-size of the entire document to 5% of the smallest viewport size (the width or the height). So for instance on an iPad (1024 x 768 px) the font-size will be 38,4 px (5% of 768 px because this is the smallest size of either viewport sizes).
Browser compatibility: https://caniuse.com/#feat=viewport-units
A better version (for me) of the solution provided by japanFour:
$(document).ready(scaleFont);
$(window).resize(scaleFont);
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth >= 1900) {$('body').attr('class','extraWide');}
else if (viewPortWidth >= 1400) {$('body').attr('class','wide');}
else if (viewPortWidth >= 1000) {$('body').attr('class','');}
else if (viewPortWidth >= 700) {$('body').attr('class','narrow');}
else {$('body').attr('class','extraNarrow');}
}
So it resizes only if window is resized (avoiding setTimout), and you give body only the exact class it needs
Beejamin's answer worked as expected, I added a set timeout so it would scale in real time. It doesn't reverse scale though.
$(document).ready(function() {scaleFont();});
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) {$('body').addClass('extraWide')}
else if (viewPortWidth > 1400) {$('body').addClass('wide')}
else if (viewPortWidth > 1000) {$('body').addClass('standard')}
else if (viewPortWidth > 700) {$('body').addClass('narrow')}
else {$('body').addClass('extraNarrow')}
setTimeout(scaleFont, 100);
}
EDIT: SOLVED REVERSE EFFECT
$(document).ready(function() {scaleFont();});
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth >= 1900) {$('body').addClass('extraWide').removeClass('wide, standard, narrow, extraNarrow')}
else if (viewPortWidth >= 1400) {$('body').addClass('wide').removeClass('extraWide, standard, narrow, extraNarrow')}
else if (viewPortWidth >= 1000) {$('body').addClass('standard').removeClass('extraWide, wide, narrow, extraNarrow')}
else if (viewPortWidth >= 700) {$('body').addClass('narrow').removeClass('extraWide, standard, wide, extraNarrow')}
else {$('body').addClass('extraNarrow').removeClass('extraWide, standard, wide, narrow')}
setTimeout(scaleFont, 100);
}
Here would be my approach (with removing actual classes + Drupal 7 jQuery):
(function ($) {
$(document).ready(function() {
var bodyClassArr = new Array('extraWide', 'wide', 'normal', 'narrow', 'extraNarrow', 'mobile');
function setBodyClass(){
// remove previous classes
for(x in bodyClassArr){
if($('body').hasClass(bodyClassArr[x])){ $('body').removeClass(bodyClassArr[x]); }
}
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) { $('body').addClass('extraWide'); }
else if (viewPortWidth > 1400) { $('body').addClass('wide'); }
else if (viewPortWidth > 1000) { $('body').addClass('normal'); }
else if (viewPortWidth > 700) { $('body').addClass('narrow'); }
else if (viewPortWidth < 700) { $('body').addClass('mobile'); }
else { $('body').addClass('normal'); }
};
setBodyClass();
$(window).resize(function() { setBodyClass(); });
}); // jquery end
}(jQuery));
Is there anything wrong with the following code? While I agree media queries are very useful, I wanted to continuously scale the font-size of certain elements of my page as the window either grew or shrunk. This code seems much simpler than the other jquery solutions of establishing class constants based on viewport pixel width:
$(document).ready(function() {
var setFontSize = function() {
var viewportWidth = $(window).width();
var fontSize = Math.sqrt(viewportWidth/250);
$('.myElement').css('font-size',fontSize+'em');
};
$(window).resize(function() {
setFontSize();
});
setFontSize();
});
Heres a simpler and no-jquery solution:
onresize=onload=function(){document.body.style.fontSize=window.innerWidth+"px"}

Categories

Resources