Disable javascript based on screen size - javascript

Okay so this maybe no possible but i think it is, i'm completely new to this so what iv'e tried might obviously not work but i didn't know at the time. My sites mobile responsive with no separate webpage for mobile sites so putting the code into a page separately won't work either.
iv'e tried:
<style>
#media screen and (max-width: 720px) {
#div {
display:none;
}
}
</style>
<div id="div">
<script type="text/javascript">
var adfly_id = ID;
var popunder_frequency_delay = 0;
</script>
<script src="https://cdn.adf.ly/js/display.js"></script>
</div>
Which didn't work. Iv'e seen this code somewhere on here
if(screen.width < 720) {
// do any 720 width stuff here, or simply do nothing
return;
} else {
// do all your cool stuff here for larger screens
}
But i don't know how i would put the adfly code into it.
EDIT:
Thanks to those who replied, iv'e got it Praveen Kumar answer worked, while weirdly it still loads the ads on the desktop regardless of the resolution it works perfect on mobiles... Siguza i'll give yours ago so people know for future reference. and i'll edit again...
EDIT II:
For future reference, Siguza's method also works so if anyone else stumbles upon this then you can take your pic on who's to use. Also Praveen Kumar method works with shortest ads too for anyone that might use them instead of adfly below is what i use.
<script type="text/javascript">
if(screen.width < 720) {
var adfly_id = null;
var popunder_frequency_delay = null;
} else {
// do all your cool stuff here for larger screens
var adfly_id = ID;
var popunder_frequency_delay = 0;
}
</script>
<script src="https://cdn.adf.ly/js/display.js"></script>
<script type="text/javascript">
if(screen.width < 720) {
//screens bigger than 720
} else {
//shortest advertisement code
}
</script>

Replace this line:
<script src="https://cdn.adf.ly/js/display.js"></script>
with this:
<script>
if(screen.width >= 720) {
document.head.appendChild(document.createElement('script')).src = 'https://cdn.adf.ly/js/display.js';
}
</script>
This will simply create a <script> tag, set its src attribute to https://cdn.adf.ly/js/display.js, and add it to the <head> tag of your document.
Just in JavaScript instead of plain HTML.
Note that I'm relying on HTML 5 here, but so are you in your question (<script> and <style> not needing a type attribute).
Edit:
This approach appears to fail on scripts that use document.write (which, IMO, is bad practice).
You can work around this by using document.write yourself:
<script>
/* you can put your adfly_id code right here */
if(screen.width >= 720) {
document.write('<script src="https://cdn.adf.ly/js/display.js"><'+'/script>');
}
</script>
Note that you must split the </script> tag in the string, or it will close the surrounding script tag, causing a syntax error.

Could be a hack-job. If this works only if you have a valid adfly_id, then do this:
if(screen.width < 720) {
var adfly_id = null;
var popunder_frequency_delay = null;
} else {
// do all your cool stuff here for larger screens
var adfly_id = ID;
var popunder_frequency_delay = 0;
}
This might fail the adfly stuff you are trying to initialize.
But the right way to do this is:
if(screen.width < 720) {
// Bye bye.
} else {
// do all your cool stuff here for larger screens
require("awesome.js");
}
ps: The require() function here is a pseudo function that would include and activate the JavaScript file. A sample of that code would be:
function loadScript(url, callback) {
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}

Related

jQuery image resizing issue

I've found this line of code somewhere using firebug and I know you need to put something where I've put the 3... behind parseFloat, but I have no idea what.
It works when I fill in a random number but the width is never the correct one and want to use it on several pages with photographs so it's always the correct size.
script type="text/javascript">
var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
$(document).ready(function(){
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
jQuery(window).resize(function() {
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
function imageresize() {
var height = $(window).height();
if ((height) > 1340){
var quality='1440';
} else if((height) > 980) {
var quality='1080';
} else if((height) > 680) {
var quality='720';
} else if((height) > 480) {
var quality='640';
} else {
var quality='320';
}
}
</script>
Thanks in advance!
It looks to me like the value you need to put there depends on the sum of the widths of all the images; so you can't just pick a value that works for all pages.
On the other hand, it also seems like a bad solution to the problem of keeping the images next to each other. Why set the width of the container? If you just ensure white-space doesn't wrap then all the images should sit next to each other without worrying about the container's width.
#container
{
white-space: nowrap; /* keep images on the same line */
font-size: 0; /* removes whitespace between images */
}
http://jsfiddle.net/f8y4Z/
From the javascript, we now only need the imageresize() (provided we use it to set different quality source images), and trigger it on ready and resize; no magic numbers required.
(For backwards compatibility with browsers that don't or poorly support white-space, you could use <nobr></nobr>)

jquery or not / Cross Browser Compatible iframe resize (IE, Chrome, Safari, Firefox)

Here is my issue. I have been looking hard for a cross browser iframe resize code to use and i just cant find one. All i have seen has issues in one browser over another. Here is what i am doing. I am loading an iframe into the page in an jquery tools overlay. This iframe will load contents of a page (on the same domain so dont need to worry about cross domain). When a user clicks an action on that form the iframe will again need to resize (i have it working for when the iframe increases but not when the iframe decreases).
I have a js file that is included in the iframe which has this function
$(window).load(function(){
parent.adjust_iframe();
});
That function then calls the parent pages function like so:
function adjust_iframe() {
//i have tried both body and html and both dont work in IE
var h = $("#overlayFrame").contents().find("body").height();
if(h==0)
h="500";
else
h=h+3;
$("#overlayFrame").css({'height': h});
window.scrollTo(0,0);
}
The above code works fine in Chrome and firefox but not in IE.
Any help here? I really need a cross browser compatible light weight solution that doesnt involve some heavy jquery plugin that isnt supported.
Thanks!
Try
$(window).load(function(){
var bodyHeight = $('body').height();
parent.adjust_iframe( bodyHeight );
});
and
function adjust_iframe(newHeight) {
//i have tried both body and html and both dont work in IE
if(newHeight == 0) {
newHeight = 500;
} else {
newHeight += 3;
}
$("#overlayFrame").css({'height': newHeight});
window.scrollTo(0,0);
}
Because the problem is probably that the page cannot access the iframes contents..
I have 2 suggestions:
When you are setting the CSS height, explicitly tell it pixels.
$("#overlayFrame").css({'height': h + 'px'});
When your iframe code is calling parent.adjust_iframe, send the current width/height.
parent.adjust_iframe($('body').height());
BONUS suggestion: Do a little investigation and tell us what version of IE and why it doesn't work. Put some alerts in there and find out if the height is getting derived etc.
I've searched my archived files and found script which sets new size of iframe window. It was working on IE6, FF,...
/**
* Parent
*/
<iframe id="myframe" name="myframe" ...>
<script type="text/javascript">
var iframeids=["myframe"];
if (window.addEventListener) {
window.addEventListener("load", resizeCaller, false);
}else if (window.attachEvent) {
window.attachEvent("onload", resizeCaller);
} else {
window.onload=resizeCaller;
}
var iframehide="yes";
var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 20 : 0;
function resizeCaller() {
var dyniframe=new Array();
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids[i]);
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i]);
tempobj.style.display="";
}
}
};
function resizeIframe(frameid){
var currentfr=document.getElementById(frameid);
if (currentfr && !window.opera){
currentfr.style.display="";
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight)
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
else if (currentfr.Document && currentfr.Document.body.scrollHeight)
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false);
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe);
currentfr.attachEvent("onload", readjustIframe);
}
}
};
function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt;
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement;
if (iframeroot)resizeIframe(iframeroot.id);
};
function loadintoIframe(iframeid, url){
if (document.getElementById)document.getElementById(iframeid).src=url;
};
</script>
/**
* child iFrame html
*/
<body onResize="resizeIE()">

How to set equal heights to a div layout with jQuery and Disqus commenting system

I have a layout that's based on div's, and uses jQuery and a "setEqualHeights" function (below) to make all the columns in my layout equal.
Equal Heights jQuery:
function setEqualHeight(columns)
{
var tallestcolumn = 0;
columns.each(
function()
{
currentHeight = $(this).height();
if(currentHeight > tallestcolumn)
{
tallestcolumn = currentHeight;
}
}
);
columns.height(tallestcolumn);
}
$(window).load(function() {
setEqualHeight($(".coln_equalize"));
});
And the HTML would be something like this:
<div id="wrap">
<div id="nav-coln" class="coln_equalize">
... navigation ...
</div>
<div id="content" class="coln_equalize">
... content ...
</div>
</div>
The setEqualHeights works fine until I add Disqus to the mix.
It seems to be loading asynchronously, causing the heights of the layout to break up and NOT be equal anymore.
The HTML code with Disqus:
<div id="wrap">
<div id="nav-coln" class="coln_equalize">
... navigation ...
</div>
<div id="content" class="coln_equalize">
... content ...
<div id="disqus_thread">
... disqus stuff ...
</div>
</div>
</div>
Sometimes I'll refresh and it's fine, and sometimes I'll refresh and it breaks up again.
Also, when I add a new comment, and that new comment appears on the page (thus adding more height), the layout breaks again.
My guess is that setEqualHeights is being applied before Disqus fully finishes loading. And it doesn't help that the new comments are adding more unknown height variables.
Is there a way to force Disqus to completely finish loading before applying setEqualHeights?
ATTEMPTED SOLUTION #1 (but failed): Only load setEqualHeights function AFTER Disqus has been fully loaded
I have searched for similar issues, and so far I came up with this thread:
Getting Equal Height Columns jQuery Plugin and Disqus to Play Nice
But the 'solution' (or lack thereof) did not work for me. There was mention of a way to force Disqus to finish loading before applying the heights function...but it didn't work when I tried the code.
I've pasted my attempt below:
function setEqualHeight(columns)
{
var tallestcolumn = 0;
columns.each(
function()
{
currentHeight = $(this).height();
if(currentHeight > tallestcolumn)
{
tallestcolumn = currentHeight;
}
}
);
columns.height(tallestcolumn);
}
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://escapology.disqus.com/embed.js';
var done=false;
dsq.onload=dsq.onreadystatechange = function(){
if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
done=true;
//CALL YOUR EQUAL HEIGHTS JQUERY CODE HERE
$(window).load(function() {
$(document).ready(function() {
setEqualHeight($(".coln_equalize"));
});
});
// (END) CALL YOUR EQUAL HEIGHTS JQUERY CODE HERE
dsq.onload = dsq.onreadystatechange = null;
}
};
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
ATTEMPTED SOLUTION #2 (also failed): Get height of Disqus block using jQuery, then adding it as a CSS height parameter using jQuery
Then I thought I might use a simpler script that would get the height of Disqus, and apply it as CSS using jQuery.
To do this, I inserted the following code in place of the "//CALL YOUR EQUAL HEIGHTS JQUERY CODE HERE" block:
$(window).load(function(){
var dynamic_height = $('div#disqus_thread').height();
$('div#disqus_thread').css({'height':dynamic_height+'px'});
});
But, again, I believe this attempt fails because it's also being applied before Disqus fully completes loading, and it also fails because it doesn't catch the new
heights being added with new comments.
ANY help would be appreciated!!

jQuery Dynamic Background-Postion for iPhone

Forgive me, I am a total n00b with javascript! I have a complicated request that I've been trying to put together for hours I think I have the pieces, but I have a poor understanding of javascript and jQuery syntax, can someone help me put this together?
First, this code should detect via UserAgent string if the device is an iPhone (Note: I'm not sure if this works for all mobile devices... any suggestions for better conditional statements that will catch ALL iPads, iPhones, etc. - anything that uses viewport rather than scrollbars)
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
{
// do stuff
}
else
{
// do nothing
}
}
</script>
Next piece of the puzzle is detecting the height of the viewport. It's important that this script be conditional and apply only to devices that utilize viewport and NOT scrollbars, otherwise I screw the site up for non-mobile users. I only need to alter background-position on the y axis, trying to prevent the background image from disappearing when mobile users slide the viewport.
var viewportHeight = $(window).height();
I found this snippet of code that utilizes the "parralax" effect - where scrolling your position affects the background-position.
$(function(){
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
xAdd = 0;
}
$('#body').css('background-position',xAdd + 'px 100%');
},10);
}); }
Can someone help me stitch all of this together... PLEASE?!
I'm thinking it should look something like this:
<script type="text/javascript">
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
$(function(){
var viewportHeight = $(window).height();
var yAdd = 0;
var scrollInterval = setInterval(function(){
yAdd++;
if(yAdd >= 920){
yAdd = 0;
}
$('#body').css('background-position',yAdd + 'px 100%');
},10);
}); }
}
else
{
''
}
}
</script>
This might not be exactly what your looking for but you can detect iphone and ipad and ipod devices through CSS like this
<link rel="stylesheet" type="text/css" href="css/iphone.css" media="only screen and (max-device-width: 480px)" />
<link rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px)" href="css/ipad.css" type="text/css" />
But I kno you need it through jQuery here is what you might do instead
jQuery(document).ready(function(){
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// do something
} else {
//do this
}
});
the only problem is this code is not specific to iPhone, iPad, iPod and so on
as far as the background-image Fixed doesn't work I know you know that makes sense why it doesn't but it sucks and I have not explored a solution for this
I don't have an official answer for this yet, but I'm CLOSE... Read Over here
https://stackoverflow.com/questions/4719469/patching-this-code-to-apply-dynamic-iphone-background-position
I've found a way to dynamically set the "top: x" property based on scroll position (at least it works on my iPhone)... but I still need help putting it all together!

How do I fire an event when a iframe has finished loading in jQuery?

I have to load a PDF within a page.
Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.
Have you tried:
$("#iFrameId").on("load", function () {
// do something once the iframe is loaded
});
I'm pretty certain that it cannot be done.
Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)
Too bad.
This did it for me (not pdf, but another "onload resistant" content):
<iframe id="frameid" src="page.aspx"></iframe>
<script language="javascript">
iframe = document.getElementById("frameid");
WaitForIFrame();
function WaitForIFrame() {
if (iframe.readyState != "complete") {
setTimeout("WaitForIFrame();", 200);
} else {
done();
}
}
function done() {
//some code after iframe has been loaded
}
</script>
Hope this helps.
I am trying this and seems to be working for me:
http://jsfiddle.net/aamir/BXe8C/
Bigger pdf file:
http://jsfiddle.net/aamir/BXe8C/1/
$("#iFrameId").ready(function (){
// do something once the iframe is loaded
});
have you tried .ready instead?
I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:
Step 1: Wrap your Iframe in a div wrapper
Step 2: Add a background image to your div wrapper:
.wrapperdiv{
background-image:url(img/loading.gif);
background-repeat:no-repeat;
background-position:center center; /*Can place your loader where ever you like */
}
Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"
The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.
Give it a try.
Using both jquery Load and Ready neither seemed to really match when the iframe was TRULY ready.
I ended up doing something like this
$('#iframe').ready(function () {
$("#loader").fadeOut(2500, function (sender) {
$(sender).remove();
});
});
Where #loader is an absolutely positioned div over top the iframe with a spinner gif.
#Alex aw that's a bummer. What if in your iframe you had an html document that looked like:
<html>
<head>
<meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
</head>
<body>
</body>
</html>
Definitely a hack, but it might work for Firefox. Although I wonder if the load event would fire too soon in that case.
I had to show a loader while pdf in iFrame is loading so what i come up with:
loader({href:'loader.gif', onComplete: function(){
$('#pd').html('<iframe onLoad="loader.close();" src="pdf" width="720px" height="600px" >Please wait... your report is loading..</iframe>');
}
});
I'm showing a loader. Once I'm sure that customer can see my loader, i'm calling onCompllet loaders method that loads an iframe. Iframe has an "onLoad" event. Once PDF is loaded it triggers onloat event where i'm hiding the loader :)
The important part:
iFrame has "onLoad" event where you can do what you need (hide loaders etc.)
function frameLoaded(element) {
alert('LOADED');
};
<iframe src="https://google.com" title="W3Schools Free Online Web Tutorials" onload="frameLoaded(this)"></iframe>
Here is what I do for any action and it works in Firefox, IE, Opera, and Safari.
<script type="text/javascript">
$(document).ready(function(){
doMethod();
});
function actionIframe(iframe)
{
... do what ever ...
}
function doMethod()
{
var iFrames = document.getElementsByTagName('iframe');
// what ever action you want.
function iAction()
{
// Iterate through all iframes in the page.
for (var i = 0, j = iFrames.length; i < j; i++)
{
actionIframe(iFrames[i]);
}
}
// Check if browser is Safari or Opera.
if ($.browser.safari || $.browser.opera)
{
// Start timer when loaded.
$('iframe').load(function()
{
setTimeout(iAction, 0);
}
);
// Safari and Opera need something to force a load.
for (var i = 0, j = iFrames.length; i < j; i++)
{
var iSource = iFrames[i].src;
iFrames[i].src = '';
iFrames[i].src = iSource;
}
}
else
{
// For other good browsers.
$('iframe').load(function()
{
actionIframe(this);
}
);
}
}
</script>
If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:
$( document ).blur( function () {
// Your code here...
});
When the dialogue pops up on top of the page, the blur event will trigger.
Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:
window.onload = function () {
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
clearInterval(self.interval);
console.log("loaded");
//You can do print here: ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
The solution I have applied to this situation is to simply place an absolute loading image in the DOM, which will be covered by the iframe layer after the iframe is loaded.
The z-index of the iframe should be (loading's z-index + 1), or just higher.
For example:
.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }
Hope this helps if no javaScript solution did. I do think that CSS is best practice for these situations.
Best regards.

Categories

Resources