How to serve up different javascript files by browser width - javascript

So I want certain Javascript files for certain browser widths. I know that #media serves up specific CSS per browser width and some devices.
How would I do something similar for Javascript files, WITHOUT using server side calls?
Is is possible with Javascript to call other Javascript files based on browser width?
If so, How?
Thanks in advance.

var scriptSrc = 'js/defaults.js';
if (screen.width <= 800)
scriptSrc = 'js/defaults-800.js';
else if (screen.width <= 1024)
scriptSrc = 'js/defaults-1024.js';
var script = document.createElement('script');
script.src = scriptSrc;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
Perhaps? Dynamic-load them based on screen resolution. Could also use document size, browser size, etc. Though I'm not positive you really want to be doing this. Ideally though you should be dealing with relative metrics (like % or em) in your design and avoid this.

While I'm unsure on why, you can always import JavaScript files through JS Script.
The following links give some information on this.
http://www.kevinleary.net/loadexternal-javascript-jquery-getscript/
http://www.stackoverflow.com/questions/1140402/how-to-add-jquery-in-js-file
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
ON a side note - Why are you looking at doing this? Surely you can get the resolution of the screen and then adjust calculations / content based on those variables without the need to change JS files. There are so many different resolutions (mobile devises, multiple monitors, wide screen, projectors etc.). A user can also re-size the browsers effectively making this not worth it.

Try this:
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
if (window.document.body.clientWidth == XXX) {
fileref.setAttribute("src", "script1.js")
} else {
fileref.setAttribute("src", "script2.js")
}

Media queries are a good solution for providing alternative styles for different window widths. Unfortunately, there is no media attribute for the <script> element to proceed similarly.
You can, however, provide a script-loading script which will load desired .js file depending on the style sheet selected by the browser on the basis of your media query. I don't know how to do this in a direct, elegant way but there is a nice hack for that. You have to "mark" each .css with a unique declaration (dummy, unimportant or different by design) and check it from within JS after the page has loaded to determine which style sheet has been applied by the browser.
The HTML could look like this:
<style media="handheld, screen and (max-width:1023px)">
body { margin-top: 0px }
</style>
<style media="screen and (min-width:1024px)">
body { margin-top: 1px }
</style>
And the accompanying JS as follows:
function onLoad() {
var head = document.getElementsByTagName('head')[0];
var body = document.getElementsByTagName('body')[0];
var mark = window.getComputedStyle(body).getPropertyValue('margin-top');
var script = document.createElement('script');
script.setAttribute('src', mark=='0px' ? 'handheld.js' : 'screen.js');
head.appendChild(script);
}
This does the job, but only on a per-load basis. To get a responsive reaction to resizing the browser's window by the user, you should keep track on the widow's width and reload the page when necessary.

Since 2011 the world has shifted into the mobile era.
You might wanna try with: document.documentElement.clientWidth, as it will tell you the visible area of your page - it reacts to zoom but not to pitch.

Related

How do I create a div the size of the page?

Note that I'm not asking how to make a div the size of the "window" or "viewport" for which there are plenty of existing questions.
I have a web page of some height and width, and I'd like to add an empty, top-level div (i.e., not one containing the rest of the page) with a size exactly equal to the page's height and width. In practice, I also want it to be at least the size of the viewport.
I know I can do a one-time calculation of the height and width in JavaScript:
var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
But this value can change based on images loading, or AJAX, or whatever other dynamic stuff is going on in the page. I'd like some way of locking the size of the div at the full page size so it resizes dynamically and on-demand.
I have tried something like the following:
function resetFakeBg() {
// Need to reset the fake background to notice if the page shrank.
fakeBg.style.height = 0;
fakeBg.style.width = 0;
// Get the full page size.
var pageHeight = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var pageWidth = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
// Reset the fake background to the full page size.
fakeBg.style.height = pageHeight + 'px';
fakeBg.style.width = pageWidth + 'px';
}
// Create the fake background element.
fakeBg = setFakeBgStyle(document.createElement('div'));
document.body.appendChild(fakeBg);
// Keep resizing the fake background every second.
size_checker_interval = setInterval(resetFakeBg, 1000);
Limitations
This is for a Chrome extension, and I'd like to limit my modification of the page to adding this single div. This means that adding CSS to modify the height and width of the html and/or body tags is undesirable because it might have side-effects on the way the rest of the page is rendered.
In addition, I do not want to wrap the existing page in the div because that has the potential to break some websites. Imagine, for example, a site styled with the CSS selector body > div. I'd like my extension to break as few websites as possible.
WHY OH WHY WOULD I NEED TO DO THIS?
Because some people like to hold their answers hostage until they're satisfied that I have a Really Good Reason™ for wanting to do this:
This is for an accessibility-focused Chrome extension that applies a CSS filter across an entire page. Recent versions of Chrome (>= 45) do not apply CSS filters to backgrounds specified on the <html> or <body> tag. As a result, I have chosen to work around this limitation by copying the page's background onto a div with a very negative z-index value, so that it can be affected by the page-wide CSS filter. For this strategy to work, the div needs to exactly imitate the way the page background would appear to a user—by being the exact size of the document (and no larger) and at least filling the viewport.
setInterval() is your best friend in cases like this where you want the .height() and .width() of an element to be asynchronously specified all the time to something that can be dynamicly altered by user input and DOM tree changes. It is what I dub as a "page sniffer", and arguably, works better than $(document).ready if you are working in multiple languages (PHP, XML, JavaScript).
Working Example
You should get away with setting the width and height in the window resize function, you might wanna add it in a load function as well, when all data/images are loaded.
just add width=100%
e.g;-
Hello World
I think you must do it like this:
...
<body>
<script>
function height()
{var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);}
function width()
{var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);}
</script>
<div height="height()" width="width()">
</div>
</body>
...

How to ignore javascript on smaller resolutions?

My dev site uses lots of Skrollr animation at 1024px resolutions and up. Under 1024px, I don't want the animation to show, so I hid all of the images and whatnot.
However, the javascript that gets called to make the animation work is still getting called on smaller resolutions and causing some issues.
Is there a way to basically say "If the resolution is less than 1024px, ignore these JS files"?
I tried putting them in a DIV and using my existing CSS media queries to "display: none" the DIV on smaller resolutions, but that doesn't work.
FYI, these are the files being called:
<script type="text/javascript" src="/js/skrollr.min.js"></script>
<script type="text/javascript" src="/js/homepageanimation.js"></script>
On top of the jQuery(function($) { in http://workwave.joomlatest01.mms-dev.com//js/homepageanimation.js put something like
jQuery(function($) {
if(screen.width < 1024) {
return;
}
// skrollr stuff....
}
so all the skrollr functions won't be called on screen sizes with a width below 1024px.
The easiest way is too use jQuery..
$(window).width();
plain Javascript:
var w = window.innerWidth;
var ow = window.outerWidth; //toolbars and status, etc...
if(w > 1024) {
//Skrollr
}
from there an small if to trigger the Skrollr event
I would suggest conditionally loading the script. Basically the script only gets loaded if the screen size is greater than 1024.
if(window.innerWidth >= 1024){
var file = document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "/js/skrollr.min.js")
}
A nice approach here would be to only call the function that initiates the Skrollr functionality at given screen sizes. A real quick Google suggests that Skrollr has a .init() function that gets things rolling.
Without seeing how the JS is set up it's hard to give any solid advice, but here's an idea:
You have a JS file for the page/site that contains a conditional that checks the width of the window before initializing the plugin after the document is ready.
$(document).ready(function() {
if ($(window).width() > 1023) {
skrollr.init();
}
});
jQuery makes this a lot easier too, so it's worth taking advantage of that.
Another option to consider instead of going via window width (which can sometimes be inconsistent with the CSS widths among different browsers) is to test against a CSS rule and whether it is true, so use one you know would be true at a size above 1024px, and this would eliminate any inconsistency.
Within this condition link the JQuery files as demonstrated in other answers.

How to run vbscript code at certain browser width

I'm turning a clients website into a responsive site and they have lots of vbscript in the content of their home page. At mobile widths they've stripped out a lot of content which means there's lots of code that's being executed but not displayed thanks to display:none
Is there a way to run vbscript code when you hit a minimum width of 768px?
I thought about using javascript to get the screen width and store it as a cookie and use vbscript to get the cookie to obtain the screen width:
<SCRIPT LANGUAGE="javascript">
var width = screen.width;
document.cookie = 'YourDomain=ScreenWidthB='+width;
</SCRIPT>
<%Dim ScreenWidth%>
<%ScreenWidth=request.cookies("YourDomain")("ScreenWidthB")%>
but I feel there may be a better solution out there. Also the code above gives me the width of my monitor I believe, not the width of the browser
This isn't something you would do with any server side language.
You can either use Bootstrap Grid System for this, which has a built-in grid system to handle responsive sizing.
or you can simply use CSS to define your styles for elements with-in a certain viewport size, using the CSS #media tag:
Your CSS would look like this example:
div {width:100px;}
#media (min-width:768px) {
div { width: 50px; }
}
What this does is makes all div's at 100px width, but when the browser is 768px or larger it changes the div sizing to 50px, as defined with-in the #media tag.
Therefore, you can use VBScript to generate the CSS script in the page, without having to write any javascript code. But Bootstrap may be your best bet to help build a responsive design easily/seamlessly. You may want to check it out.
EDIT: Since OP has clarified not to even load the content
You can make a cookie in javascript, and read it in your VBScript to check the viewport.
You can use jQuery for this:
$(window).resize(function(e){
var w = $(this).width();
if(w>768) document.cookie = "viewport=768;";
else document.cookie = "viewport=;";
});
This will bind an event listener on any time the user resizes the window, to check it's size, and if above 768px, it will write the cookie or empty if not.
Then check for the viewport cookie using Request.Cookies("viewport")
Or better yet since you're concerned about performance, you can use Ajax to build your page when a certain viewport size is hit.
Again, you can use jQuery for this and bind to the window resize event.
contentloaded = false;
$(window).resize(function(e){
var w = $(this).width();
if(w>768 && !contentloaded) {
$.get(url,function(data){
$("div").html(data);
contentloaded = true;
});
}
});
I would use ajax to do this, since I'd want to show the content without the user having to refresh the screen as you would have to by using the cookie solution.

Load different CSS stylesheet using JavaScript reading from URL variable

I am trying to have two different stylesheets on my wordpress blog, so that one stylesheet is used when the page is accessed via the web, and the other stylesheet is used when the blog content is accessed via our iOS app. Right now we are appending ?app=true to URL requests from our iOS app in hopes that in our blog we could search for this string and load a different stylesheet. We are using a JSON API plugin so that our iOS app can programmatically pull our blog posts and display them in a web view in the iOS App.
In my wordpress blog I am using JavaScript that looks for ?app=true in the URL, and if so, load a different stylesheet.
<script language="javascript" type="text/javascript">
var currentLocation = window.location.href;
if(currentLocation.indexOf('/?app=true') > -1) {
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"appstyle.css\" />");
}
</script>
You can take a look at http://blog.meetcody.com and view the page source. You will see this code snippet in-between the tags.
The issue that I'm having is that the above code doesn't actually load the appstyle.css stylesheet. If you take a look at http://blog.meetcody.com/wp-content/themes/standard/appstyle.css?ver=3.4.2 you can see that I'm testing this by setting the background: black in the body {} tag
body {
background: black;
}
Whereas, in style.css at http://blog.meetcody.com/wp-content/themes/standard/style.css?ver=3.4.2 the body background color is #F2F0EB; in the body {} tag
body {
background: #F2F0EB;
}
How can I pass a URL variable such as ?app=true and when that is passed, I load a different stylesheet?
I believe that the best way to approach your problem is to employ Responsive Web Design techniques. These allow you to address different resolutions appropriately.
The basic CSS looks something like the following...
#media screen and (min-width: 480px) {
// CSS for iPhone
}
#media screen and (min-width: 768px) {
// CSS for iPad
}
#media screen and (min-width: 900x) {
// CSS for desktop
}
The take-away is that you won't need to load different stylesheets for different platforms. You'll have one stylesheet that works in every situation. It can even work for platforms you haven't specifically targeted.
The team the built the new Boston Globe site were my introduction to RWD. Here's a breakdown of what they did.
I tried some things with the Firebug console on your site. So, what actually worked was the following code:
<script type="text/javascript">
if(window.location.href.indexOf('/?app=true') > -1) {
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "http://blog.meetcody.com/wp-content/themes/standard/appstyle.css");
document.getElementsByTagName("head")[0].appendChild(fileref);
}
</script>
(This code was adapted from Dynamically loading an external JavaScript or CSS file).
Since your are loading other stylesheets and I guess you overwrite their rules, you have to load this stylesheet AFTER all the others. So put this code at the end of your document or in a window.onload event.
You could also sniff out the user-agent string. This way you wouldn't have to pass anything. In most cases I wouldn't recommend it usually but with such a specific case you can safely do it without a ton of code.
// Define what "webview" is
var is_uiwebview = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);
// See if this user is coming from it
if (is_uiwebview = true) {
// Your code to make the <link> with a proper href
// Raul's would work perfectly
};
Again, as everyone else said make sure it loads things after your web-only stylesheet.
Also not entirely sure the = true is needed.

Dynamic resizing of page

I am a newb to JavaScript, but am trying to learn. For that reason I would like to try and accomplish this without resorting to jQuery.
I am trying to load a page where the content is dynamically re-sized based on the height and width of the browser. I presently have two iterations of the code, one with an image in the content div and another, much simpler, without.
Firstly, addressing the one without the image. Calling winSizefrom an onload event in the body tag or inside the script tag at the bottom of the HTML seems to be able to determine the scrollHeight/Width prior to setting the style, but fills the entire window with the black of the content div rather than setting its width to 704px as the script has determined it should be. Using the document.body.onload in the script header to call winSize resulted in a null scrollWidth/Height and only displays the grey background.
The code for that is as as follows:
<style>
body {
padding:0px;
background-color: #808080;
}
div {
position:absolute;
}
</style>
<script type="text/javascript">
bArat=3/2;
bH1=0;
bW1=0;
bX1=0;
bY1=0;
function winSize(){
winW=document.body.scrollWidth;
winH=document.body.scrollHeight;
_style();
}
function _style(){
bH1=winH;
bW1=bH1/bArat;
bX1=(winW/2)-(bW1/2);
document.getElementById("gutters").style.left=bX1;
document.getElementById("gutters").style.top=bY1;
document.getElementById("gutters").style.height=bH1;
document.getElementById("gutters").style.width=bW1;
document.getElementById("gutters").style.backgroundColor="black";
document.body.style.backgroundColor="black";
}
//document.body.onload=winSize();
</script>
</head>
<body>
<div id="gutters">
</div>
<script>
//winSize();
</script>
</body>
</html>
Secondly, in the more complicated version of this script that includes a div within "gutters" that houses an img (soon to be multiple, as soon as this problem is solved), almost everything works fine except for when it loads, it does not load the styles (in Chrome). It does, however, load the styles on a refresh or if I set a 50ms delay on the onload trigger. I presume this is because Chrome (and Safari?) triggers the onload event after the html has loaded but before the image itself has been rendered, therefore the function cannot determine the height and width of the body that has not truly finished loading.
In this second script the function above:
function winSize(){
winW=document.body.scrollWidth;
winH=document.body.scrollHeight;
_style();
}
does not work at all. winH or winW are not defined.
but the function snagged from http://www.javascripter.net/faq/browserw.htm
function winSize(){
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
}
}
works as described above: "...when it loads it does not load the styles (in Chrome). It does, however, load the styles on a refresh." If I run this second winSize function in the first script it returns the error "Cannot read property 'style' of null".
I prefer the first function for its brevity and (according to W3schools.com) better cross browser compatibility with object.scrollWidth over window.innerWidth, but clearly, one or both are broken in some context.
My questions are, in order of importance:
In the second script, how can I get the 'winSize' function to run after the images have fully loaded? (if that is the issue)
Why are the two scripts having such drastically different reactions to the two functions when implemented in the same way.
What would fix the first script that I presented--where the first content div, "gutters", is filling the entire screen rather than making a rectangle.
Why putting an onload event in the body tag works, but putting document.body.onload in the script of the head doesn't.
Sorry for such a long question--and so many questions in one, but I couldn't figure a way to untangle them. I would appreciate any help and forever praise those who can help me wrap my head around this.
why not just specify dimensions in % and let the browser do it.
May be you have some very specific requirement?
Please write the scenario, (in short)

Categories

Resources