I'm new to php. I have a doubt, don't know if this can be done, or if it should be done in another way or what.
I want to load a JS only if the screen size is higher than x size.
I wrote this but the JS is not being loaded (in fact I want to load a couple of JS):
<script language="javascript">
if (screen.width > 549) {
<script src='js/jquery-1.8.1.min.js' type='text/javascript'></script>
}
best regards!
php cannot detect a clients screen width/height, that all would have to be done client side.
function addScript(src){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
document.head.appendChild(script);
}
if(screen.width > 549){
addScript("js/jquery-1.8.1.min.js");
addScript("js/someOtherScript.js");
}
It's cleaner to detect the screen width in JavaScript. Also remember the screensize can change in a session. For example when a user resizes his screen.
Use this in your JavaScript file:
var width = document.body.clientWidth;
if(width > 549) {
} else if(width < 300) {
} else {
}
You cannot determine a clients' browser window size before a client has received a page with PHP.
Technically you could load a page, get javascript to send back the window size and then store it in the session for that user, but I don't really see the point. You're better off either always including the javascript file, or using a javascript library to conditionally add other scripts to the DOM.
Related
I am trying to resize the page based on the size of the window. I need the size of the window on the page load and when the window is being resized.
I've looked online and I found a way to do this with javascript. The problem with this is that javascript gets fired after the page_load. I know it's not possible to get javascript values before the page load, so how am I able to use the values from javascript in my code? Can I use another page that with javascript determines the size of the window, and pass it to my main page?
I hope this is clear. Thank you!
No. you cann't get window size from the server side. However, here is what you can do in javascript assuming you are using jQuery:
var width = $(windows).width(),
height = $(window).height();
After getting these values, pass them through an Ajax call to the server:
$.ajax({
method:'POST',
data: { w : width, h: height},
// complete your ajax
});
You won't get page or windows size at server side i.e on page load function, but you will get it using client side script i.e jquery or javascript
<script type="text/javascript">
$(document).ready(function()
{
var w = $(window).width();
var h = $(window).height();
});
</script>
And later on you can do your functionality when resize the window by using following function
window.onresize = function(event)
{
var height=$(window).height();
var width=$(window).width();
//your functionality
}
I have this piece of javascript for my responsive site (See below).
In a nutshell, I don't want it to display (meaning I don't want this javascript to execute) when the screen size is below 480 (mobile phone). How would I do that? I tried using display:none for the div that it's in, but the script still executes and the Hello Bar still shows. Any ideas? Thanks.
<script type="text/javascript" src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js"></script>
Here's the website: http://www.thesandiegocriminallawyer.com
Here's the HTML (near the bottom):
<div class="hello_bar">
<script src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js" type="text/javascript">
</div>
Measure the screen width and only attach the hellobar script if its wider than 480:
Replace:
<script type="text/javascript" src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js"></script>
With:
<script type="text/javascript">
var swidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if (swidth > 480) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js";
document.getElementsByTagName('head')[0].appendChild(s);
}
</script>
http://jsfiddle.net/xusH3/
There are 2 solutions I can think of:
Load the script dynamically by checking the width of the screen first and then loading the file in an asynchronous way if needed.
Wrap the content of your script file in a condition that is based on the width of the screen/document (the file will be loaded anyway but won't run anything if screen is below 480)
The first way is better, while the second can solve headache if you need your code to be available immediately when the page loads
A sample for loading script in an async way is:
<script>
function loadScript(url){
var js, fjs = document.getElementsByTagName('script')[0];
js = document.createElement('script');
js.src = url;
fjs.parentNode.insertBefore(js, fjs);
};
if(window.innerWidth>480){ //here you should check for the width (this check is not necessarily cross browser)
loadScript("//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js");
}
</script>
So I am trying to find the height of my images then add a top margin this enables me to impose a a vertical center.
I'm running this code, and on an F5 refresh I get correct height but on CTRL+F5 refresh it gives me a much smaller height. I kind of assume this is a loading/delay thing, but I am using document ready so not really sure whats going on. I tried using a php function but it slows the site down amazingly so have to stick with jquery.
you can see it working here. www.mzillustration.com
jQuery(document).ready(function() {
if (jQuery('.imagedisplay').length != 0) {
jQuery('.imagedisplay').each(function(){
var imgheight = jQuery(this).find('img').height();
var topmarg = ((240 - imgheight) / 2) ;
jQuery(this).find('img').css({'margin-top':topmarg+'px'});
});
});
any ideas/help/explanation much appreciated.
thanks
There is a difference between onload and onready.
ready will wait until the actual DOM-tree is done, while onload will wait until ALL of the content displayed on the page is finnished loading. So an explanation would be that when clearing the cache and refreshing, the dom tree finishes much faster than the images, hence giving the wrong heigh.
Try using the onload-event instead and see if you get a different result.
You need to insure the image has loaded before asking the browser for its height. If that image path is living in the html you will unfortunately need a jquery pluggin to handle this in a cross browser manner.
https://github.com/alexanderdickson/waitForImages
http://desandro.github.com/imagesloaded/
Or you will have to wait for the window.onload event which in jquery looks like this:
$(window).on('load', function(){....
However if you use the window load event, it will wait until ALL resources have loaded and depending on your site that can be a serious delay when compared to measuring just the image itself.
Or if you are comfortable with loading the image from javascript, simply ordering your code properly will handle this:
var loadTester = new Image(),
imgH;
$(loadTest).on('load',function(){
imgH = $('#image').attr('src',loadTester.src).height();
}
loadTester.src = "paht/to/image.jpg";
The reason you are seeing a difference in the manner you reload the page, is that a simple refresh does not clear the cache, so the image is already loaded. When you hit ctrl+f5 it clears the cache and so the image is not yet loaded when you ask the browser for the height.
For cache control durring development consider getting the firefox web-developer toolbar.
Try this approach:
jQuery(function() {
jQuery('.imagedisplay img').each(function() {
var $this = jQuery(this),
height = $this.height();
if (height) {
$this.css('margin-top', ((240 - height) / 2) + 'px');
} else {
$this.on('load', function() {
$this.css('margin-top', ((240 - $this.height()) / 2) + 'px');
});
}
});
});
images are/can be cached/loaded separately from the actual page content. the document being ready can (and in my experience usually) occurs before everything is loaded.
try adding an event listener to the actual element being loaded.
You need to make sure the image has loaded before extracting a height. You can easily check this using the complete property on the image. Try this:
var setH = function() {
$(this).css('margin-top', (240 - this.height) / 2);
}
$('.imagedisplay img').each(function() {
if( this.complete ) {
setH.call(this); // apply height straight away
return;
}
$(this).load(setH); // apply height when the image has loaded
});
Okay, so I'm working on a responsive site and I'm trying to handle Adsense in the best way possible that doesn't get me banned! What I'd like to do is use jQuery to add in my Adsense code only if the browser width is less than 533px. This way, I can display a smaller ad that will fit the window properly and not break the layout. I'm having some trouble getting the Adsense javascript added though. This works:
(function($){
//detect the width on page load
$(document).ready(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 533){
$('.ads').prepend("THIS IS WHERE I WANT THE ADSENSE CODE TO GO");
}
});
But when I include my Adsense code to replace THIS IS WHERE I WANT THE ADSENSE TO GO, it doesn't. This is the Adsense code:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-1234567890";
/* Test Ad */
google_ad_slot = "1234567890";
google_ad_width = 250;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
I've also tried to include the Adsense javascript code in a .html file and use jQuery.get and jQuery.getScript for a .html and .js file. I just can't get it to work.
I could do it with a simple PHP header detect, but I want the ads to display based on width, not device type.
Anybody know how this can be done?
(Reposted as no replies to previous question)
I'm not sure if this will work or not, but it's worth a shot:
/* these should be global */
google_ad_client = "ca-pub-1234567890";
/* Test Ad */
google_ad_slot = "1234567890";
google_ad_width = 250;
google_ad_height = 250;
$(function(){
//detect the width on page load
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 533){
$.getScript('http://pagead2.googlesyndication.com/pagead/show_ads.js');
}
});
The problem you're facing is that Google doesn't really support AdSense ajax. The normal way of including adsense code uses the URL of the page where it lives in order to render the right content.
Now, suppose you could reduce the adsense code to a particular URL. You could do something like this:
// note, this url is just a suggestion, not something that will likely work
var url = 'http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-1234567890&ad_slot=1234567890&ad_width=250&ad_height=250';
var adsContainer = $('.ads'); // though, if there's only one, use id, not class
$.ajax({
type:'GET',
url:url,
async:true,
success:function(html) {
adsContainer.html(html);
return false;
},
error: function(html) {
adsContainer.html('SOME DEFAULT AD MESSAGE');
return false;
}
});
But I think this is almost assuredly the kind of thing that will get you in trouble with Google.
Google used to have an adsense ajax program:
https://developers.google.com/adsense-for-ajax/
But it is now "unavailable". The reason you can't put your code in an external .html or .php file and ajax on your own server is that the javascript doesn't get executed by an engine on the client side by the ajax call. You are injecting raw javascript into a page that has already been interpreted by the javascript engine.
Could you use node.js or some kind of server side javascript parser to serve your .html file? Maybe, but that's a lot to solve this problem.
My advice is this: include multiple, smaller ads that will look good if stacked on a big page, or tiled if crammed together on a small page.
Have you tried lading the external .js like this?
var script = document.createElement('script');
script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
script.type = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
Working on a Mobile First design and want to conditional load and execute some JavaScript based on the browser width.
UPDATE: (more info on what I'm doing)
I'm looking to conditionally load different size Google DFP ads depending on the width of the browser window. So a desktop/iPad might see a 720 pixel wide ad, a wide mobile might see a 480px ad and a basic mobile might see a 320px ad.
Google DFP has an asynchronous method which has the main code in the head. Ad calls are then made via a combination of a div with a numbered id and a function call that has the same number.
So in what I'm trying to accomplish, I need to insert both a numbered div and a specific numbered function call into the div where I want the specific ad call to appear.
Looked around for conditional examples and this worked in my test:
<div id="ad"></div>
<script type="text/javascript">
var ad = document.getElementById("ad");
if (document.documentElement.clientWidth > 640) {
ad.innerHTML = "big";
}
if (document.documentElement.clientWidth < 640) {
ad.innerHTML = "small";
}
</script>
Obviously just a test of the width checking and not the ad call.
If I understand correctly, innerHTML won't work if I need to dynamically load and execute some JavaScript.
Basically, when I test for the size I have to enter an ad call like this into the #ad div:
<div id='div-gpt-ad-xxxxxxxxxxx-2'
style='width:728px;height:90px;margin:auto'><script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-xxxxxxxxxxx-2'); });
</script></div>
Notice the "-2" in both the div and function. That will be different for the different ad sizes.
Completely new to DOM manipulation so any help is greatly appreciated.
You are correct that script elements inserted using the innerHTML property aren't executed.
A simple solution is to collect the script elements that were inserted and replace them with new elements where the code will be executed, e.g.
function insertAndExecute(id, markup) {
var sOld, sNew, scripts;
var s;
var el = document.getElementById(id);
if (el) {
s = document.createElement('script');
el.innerHTML = markup;
scripts = el.getElementsByTagName('script');
for (var i=0, iLen=scripts.length; i<iLen; i++) {
sOld = scripts[i];
sNew = s.cloneNode(true);
sNew.type = sOld.type;
if (sOld.src) {
sNew.src = sOld.src;
} else {
sNew.text = sOld.text;
}
sOld.parentNode.replaceChild(sNew, sOld);
}
}
}
It is much better if the scripts have a src attribtue and load an external file.
As jfriend00 says, if you can determine the markup to be inserted during page load, document.write is a viable alternative as it will cause included scripts to be executed. But you can't use it after the page has finished loading.
Edit
As for getting the width of the window:
var width = window.innerWidth || document.body.clientWidth;
should do. Note that in IE, clientWidth is 20px less than the window width because it allows for a vertical scroll bar. But that shouldn't matter here.
Also, clientWidth shouldn't be measured until the document has finished loading so the layout is complete (use onload or something later), and make sure documents have a DOCTYPE so that IE is in standards mode (or "almost standards mode" or whatever).
You might also be interested in How to Measure the Viewport.
If you're new to DOM manipulation, then stop right now and find a JavaScript library that you like. The DOM is by far the most frustrating part of using JavaScript in the browser, so don't ruin your first experience with the language by not using a library that helps you with it. Two good options are YUI and jQuery. This is important because you can't get the width of the screen reliably with document.documentElement.clientWidth. Different browsers use different properties for it.
Regarding your question, in this case it's just a matter of running the code in your script after inserting the content into the ad container.
<div id="ad"></div>
<script>
document.getElementById('ad').innerHTML = '<div id="div-gpt-ad-xxxxxxxxxxx-2" style="width:728px;height:90px;margin:auto"></div>';
if (screenWidth > 640) {
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-xxxxxxxxxxx-2');
});
} else {
// do something else
}
</script>