Straight Reload/Refresh of DIV Contents on Window Resize Using - javascript

I'm adding Amazon Affiliate banners to my website, but because the banner code isn't responsive, the larger size banners break out of my container in the smaller sizes. I've created the following code so that when the page initially loads, it will load an appropriate sized banner in the correct space. However, I would like to set it so that when the browser window is resized, the DIV containing the banner code (bannerdiv) is refreshed and the script is re-executed.
I'm a novice at this, so your patience and idiot-simple instructions will be appreciated. I'm also sure this code is written in a painfully clunky manner.
NOTE: I've updated the code per suggestions in the comments, but it's still not working. Any suggestions?
<script type='text/javascript'>
function loadBanners() {
function lrgBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'AC2XN3SJ34RJMGYK';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '48';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '1XTRE8BRWXGWQJTWPJ82';
amzn_assoc_width = '728';
amzn_assoc_height = '90';
}
function medBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'OTLU2UB6UY5JMUHP';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '26';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '0CDY3FGJ2PD68NJXFKG2';
amzn_assoc_width = '468';
amzn_assoc_height = '60';
}
function smlBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'G7YQZ5D43772NXLC';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '42';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '1VHGPZ2J9GDJGYKD5G82';
amzn_assoc_width = '234';
amzn_assoc_height = '60';
}
var winwidth = window.innerWidth;
if (winwidth >= 1200) {
lrgBanner();
} else if (winwidth < 980 && winwidth >= 920) {
lrgBanner();
} else if (winwidth >=980 && winwidth < 1200) {
medBanner();
} else if (winwidth >= 600 && winwidth < 920) {
medBanner();
} else {
smlBanner();
}
}
loadBanners();
</script>
<div id="bannerdiv">
<script id="bannerscript" src='//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1'></script>
</div>
<script type="text/javascript">
function amznScript() {
var banDiv = document.getElementById('bannerdiv');
var oldScript = document.getElementById('bannerscript');
var newScript = document.createElement('script')
newScript.type = 'text/javascript';
newScript.src = '//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1';
newScript.id = 'bannerscript'
banDiv.replaceChild(newScript,oldScript);
}
</script>
<script type="text/javascript">
function adBanner() {
loadBanners();
amznScript();
}
window.addEventListener("resize", adBanner);
</script>

Found something related to Amazon banners here:
Amazon Associates Site

I don't have experience with this particular library, but I'll share some thoughts just looking at your code:
Do the docs say the numeric variable settings need to be strings or numbers? (amzn_assoc_width, amzn_assoc_height, etc). Usually, number should be without the quotes (amzn_assoc_width = 234 instead of amzn_assoc_width = '234')
Take the lrgBanner, medBanner, and smlBanner functions OUT of the loadBanners function. You have them defined inside of it. loadBanners will work fine with them outside.
Because you're defining the variables inside of functions, they may not be getting set where the Amazon script can see them (the global space). In your browser, after the page loads, open the browser console and type in the name of any of the variables in the console and it will output whatever the variable is set to. If it outputs undefined, either you're doing something wrong in the console or the variables aren't being set in the global space. Additionally, try typing window.variableName in the console to double check.
Related to the previous bullet, try prefixing all the variable definitions in your functions with window. to explicitly set them in the global space, which is where the Amazon script is probably expecting to find them.

If you can't use responsive banners for your category, try just dynamically loading the banners using the iframe banners. Here's an example using jQuery
<head>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script language="javascript">
$(window).on('load resize', function() {
winWidth = $(window).width();
if ( winWidth >= 1200) {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=48&l=ur1&category=home&banner=1T8X6QB60F8G26A33RG2&f=ifr&linkID=WHAOQICV37C7EWOX','width':'728','height':'90'})
} else if (winWidth >= 600 && winWidth < 1200) {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=26&l=ur1&category=home&banner=017THAMGVS89AQ891982&f=ifr&linkID=5ORSSCSEHTUJ6JZS','width':'468','height':'60'})
} else {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=42&l=ur1&category=home&banner=1VCFP7EH9H4CBCD6ADR2&f=ifr&linkID=IHZPNRGMTYWEIYAS','width':'234','height':'60'})
}
});
</script>
</head>
<body>
<iframe id="myBanner" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
</body>
Using a blank iframe for the initial load helps to prevent the banner from changing while the page is loading.
Hope that helps!

Related

Iframe fetching the full screen method from iframe source

I try to create a one liner iframe that users can add in their sites and this iframe adress is my site.
My problem is that if i want it to be able to become full screen i need to supply them with js code and i don't want it i want it to fetch the js code from my site.
The js that i use to make full screen when needed is :
<script>
window.addEventListener('message', receiveMessage, false);
function receiveMessage(evt) {
if (evt.origin === 'site src') {
//if (isNaN(evt.data)) return;
var iframe = document.getElementById('someId');
if (event.data.height !== 0) {
iframe.height = 100 + "%";
iframe.width = 100 + "%";
iframe.style.position = 'fixed';
iframe.style.top = '2%';
iframe.style.left = '2%';
}
else {
iframe.height = 110 + "px";
iframe.width = 300 + "px";
iframe.style.position = 'relative';
}
}
}
</script>
This script currently written at the client the one that use the iframe.
The iframe looks like.
<iframe id="expertips_iframe" src="my site adress" width="300px" height="110px" frameBorder="0" scrolling="no"></iframe>
I want the iframe line to fetch the js code from my site and inject it to the user/client that use the iframe, or any other way as long as i do it (the iframe and the js) in one line.
Hope it is clear enough and thank you.

Optimizing performance of a javascript image animation

I've got a question in regards to javascript and dynamically displaying images to
form an animation.
The pictures I have are around 1360x768 in size and quite big despite being .png pics.
I've come up with a code for switching out the pics dynamically, but even run on a local
webserver it is too slow (thus sometimes I see the pic being built).
So my question is: is there a better way to do this than dynamically switching out
the "src" part of the image tag, or is there something else that could be done in combination with that, to make sure that the user doesn't have any strange phenomenons
on the client?
<script>
var title_index = 0;
function display_title()
{
document.getElementById('picture').src=
"pics/title_" + title_index + '.png';
if (title_index < 100) {
title_index = title_index + 5;
setTimeout(display_title,3000);
}
}
</script>
<body onload="setTimeout(display_image,3000)">
<image id="picture" src="pic/title_0.png"/>
</body>
Thanks.
I've had this problem too, even when preloading the images into the cache,
Google's The Hobbit experiment does something interesting. They do low resolution while animating and switch it for a hiresolution if you "pause" (stop scolling in the case of The Hobbit experiment). They also use the HTML5 canvas tag to smooth out the animation.
Here's their blog post about their method:
http://www.html5rocks.com/en/tutorials/casestudies/hobbit-front-end/
Their end product:
http://middle-earth.thehobbit.com
Edit:
Pre loading example:
<!Doctype html>
<head>
<title>test</title>
</head>
<body>
<canvas id="myCanvas" width="1360" height="768"></canvas>
<script type="text/javascript">
var images = {};
var loadedImages = 0;
var numImages = 0;
var context = '';
function loadImages(sources, callback)
{
// get num of sources
for(var src in sources)
{
numImages++;
}
for(var src in sources)
{
images[src] = new Image();
images[src].onload = function()
{
if(++loadedImages >= numImages)
{
callback(images);
}
};
images[src].src = sources[src];
}
}
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
var sources =
{
frame0: 'http://piggyandmoo.com/0001.png',
frame1: 'http://piggyandmoo.com/0002.png',
frame2: 'http://piggyandmoo.com/0003.png',
frame3: 'http://piggyandmoo.com/0004.png',
frame4: 'http://piggyandmoo.com/0005.png',
frame5: 'http://piggyandmoo.com/0006.png',
frame5: 'http://piggyandmoo.com/0007.png',
frame5: 'http://piggyandmoo.com/0008.png',
frame5: 'http://piggyandmoo.com/0009.png'
};
var width = 1360;
var height = 768;
var inter = '';
var i = 0;
function next_frame()
{
if(numImages > i)
{
context.drawImage(images['frame' + (i++)], 0, 0);
}
else
{
clearInterval(inter);
}
}
loadImages(sources, function(images)
{
//animate using set_timeout or some such...
inter = setInterval(function()
{
next_frame();
}, 1000);
});
</script>
</body>
Code modified from: www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/
You could overcome this issue by preloading the images on page load. This means that the images would then be stored in memory and immediately available to you. Take a look at the following:
JavaScript Preloading Images
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Can you get a users screen size/resolution using javascript?

Is there a way to get the a users screen size/resolutions using javascript? I figured you probably can't use PHP to do this as it's server-side, but as javascript is client-side I thought it may be an option.
Yes, you can use the following to print out the resolution for example:
<script type="text/javascript">
document.write(screen.width+'x'+screen.height);
</script>
Might not work in older browsers, but will in most recent ones.
More info here:
http://www.javascriptkit.com/howto/newtech3.shtml
Yes i have used the following code and it works well.
var screenW = 640, screenH = 480;
if (parseInt(navigator.appVersion)>3) {
screenW = screen.width;
screenH = screen.height;
}
else if (navigator.appName == "Netscape"
&& parseInt(navigator.appVersion)==3
&& navigator.javaEnabled()
)
{
var jToolkit = java.awt.Toolkit.getDefaultToolkit();
var jScreenSize = jToolkit.getScreenSize();
screenW = jScreenSize.width;
screenH = jScreenSize.height;
}
document.write(
"Screen width = "+screenW+"<br>"
+"Screen height = "+screenH
)
Courtesy: http://www.javascripter.net/faq/screensi.htm

JavaScript Preloader in Modal Div from HTML Table concatenates to new img URL

This code is meant for a real estate website I am updating for my company. Basically, There is a table with the property name, address, etc, and an image. Originally, I was coding this website in ASP.net switch over to regular Javascript for a few reasons (hosting overhead etc).
Sections of this code are from a few different tutorials out there, one of which is an ASP.net modal div image "enlarger" tutorial, which is sort of the basis combined with a few other sites. I have yet to comment in their names etc, but I plan on giving them credit in the code. Thier links are below before I post my code.
http://archive.aspsnippets.com/post/2009/07/06/Image-Gallery-using-ASPNet-GridView-control.aspx
My code is essentially as follows (I will trim the fat and excess line breaks in the style section):
First are the modal style tags from that tutorial by Mudassar Khan (partially relevant):
<style>
body {margin:0;padding:0;height:100%;}
.modal {display: none;position: absolute;top: 0px;left: 0px;background-color:black;z-index:100;opacity: 0.8; filter: alpha(opacity=60);-moz-opacity:0.8;min-height: 100%;}
&#divImage{display: none;z-index: 1000;position: fixed;top: 0;left: 0;background-color:White;height: 550px;width: 600px;padding: 3px;border: solid 1px black;}
<style>
Then comes his script, which I may have tweaked here and there:
<script type="text/javascript">
function LoadDiv(url) {
var img = new Image();
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
var imgLoader = document.getElementById("imgLoader");
img.src = url;
var tcopy = img.src.slice(0,(img.src.length-4)) + "_big.png";
img.src = tcopy;
img.onload = function () {
imgFull.src = tcopy
imgFull.style.display = "block";
imgLoader.style.display = "none";
};
var width = document.body.clientWidth;
if (document.body.clientHeight > document.body.scrollHeight) {
bcgDiv.style.height = document.body.clientHeight + "px";
}
else {
bcgDiv.style.height = document.body.scrollHeight + "px";
}
imgDiv.style.left = (width - 650) / 2 + "px";
imgDiv.style.top = "20px";
bcgDiv.style.width = "100%";
bcgDiv.style.display = "block";
imgDiv.style.display = "block";
return false;
}
function HideDiv() {
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
imgLoader.style.display = "block"; // I added as it seems to bring back the loader gif
if (bcgDiv != null) {
bcgDiv.style.display = "none";
imgDiv.style.display = "none";
imgFull.style.display = "none";
}
}
</script>
Now All this above script gets called upon a onClick Event Handler on an image of each of the real estate companies properties. This will work well to both preload images with the little animated gif and the close button works fine. It works on more than one image, BUT if the image is already preloaded, I cant think of a way to force the redisplay of an already preloaded image if a user clicks on the photo, then clicks close to hide the div tag and then clicks on the same preloaded image.
That event handler looks like this:
img onClick="return LoadDiv(this.src);" src="http://www.ourcompany.com/images/prop_thumbs/Some_plaza.png" style="min-width:200 px;max-height:150 px;max-width:200 px;"
I thought global booleans would work, but then I realized, theres no telling which and what is preloaded, so the boolean might not help if you can't pass something meaningful back and forth.
I'm not asking any one to do my work for me, however I would appreciate suggestions in the right direction.
Regards and TIA!
You could make a array of all of the images with key values of loaded. For instance.
image_list = {image1:false,image2:true,image3:false};
true and false being loaded or not loaded. When an image is clicked just update the array.
image_list[image1] = true;
Did this really quick, so my syntax might be off, feel free to correct me or berate me...
Yay!!! Figured it out with the help of both jhanifen and the guy who did the tutorial I used (he actually emailed me). My code is below (its an excerpt, but you'll get the idea):
images = new Array(30);
//need to define each image to be in array
images[0]="website/images/prop_thumbs/property1_big.png";
images[1]="website/images/prop_thumbs/property2_big.png";
images[2]="website/images/prop_thumbs/property3_big.png";
//This continues for some time
imagesLoaded = new Array(30);
// per stack overflow person suggestion make array of bool values; initialize them all to false on page load
function onLoadScript() {
for (i = 0; i < imagesLoaded.length; ++ i)
{
imagesLoaded [i] = false;
}
}
// the above is called onLoad in body tag
// Changes the script for Loading the Div tag are below:
function LoadDiv(imgNum) {
var img = new Image();
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
var imgLoader = document.getElementById("imgLoader");
img.src = images[imgNum];
if(imagesLoaded[imgNum] = true)
{ // this statement triggers same as onload below!
imgFull.src = img.src
imgFull.style.display = "block";
imgLoader.style.display = "none";
}
img.onload = function () {
imgFull.src = img.src
imgFull.style.display = "block";
imgLoader.style.display = "none";
imagesLoaded[imgNum] = true;
};
The rest of the document is the same except I changed the onClick event handler for the property images to LoadDiv(and some sequential number);
Thanks to all for your help! Particular props to both Mudassar Khan and jhanifen!

How would use javascript to open an image in a separate window after I resize it?

This is the code that I have to re-size the image for me. What I don't know how to do is have the code open the image after it has been re-sized.
So what I wish for it to is is
Resize the image(It is already doing this).
Once image is re-sized, open it in a separate window
This is the code that re-sizes the image for me.
function resize(which, max) {
var elem = document.getElementById(which);
if (elem == undefined || elem == null) return false;
if (max == undefined) max = 1024;
if (elem.width > elem.height) {
elem.width = max;
elem.height = 768;
}
}
That code does not actually resize the picture, it just changes how it is displayed. If the image is downloaded or opened in a separate window, it will be the dimensions of the original image. I don't think there is any way of modifying the image through JavaScript.
What you could do, though, is find a program that can do that for you and call that through an Ajax call. For example, I think the Gimp can handle that, and if you can call that from a PHP script, then you can call that PHP script through an Ajax call and display that. It's kind of a complicated solution but that's the best I can think of.
As tjameson pointed out, JavaScript doesn't really resize your image.
If you want to take this image to a new window, here is a way to do it:
var im = document.getElementsByTagName('img')[0];
var w = window.open("");
var b = w.document.body;
b.appendChild(im);
You can apply the resize function on this image if you want it displayed resized.
I appended the needed code to the initial resize function
function resize(which, max)
{
var elem = document.getElementById(which);
if (elem == undefined || elem == null) return false;
if (max == undefined) max = 1024;
if (elem.width > elem.height)
{
elem.width = max;
elem.height = 768;
}
var f = window.open("", "_blank", "height=500, width=600,toolbar=0, menubar=0, scrollbars=1, resizable=1,status=0, location=0, left=10, top=10");
f.document.title = elem.alt;
f.document.body.innerHTML += '<img src="'+elem.src+'" height="'+elem.height+'" width="'+elem.width+'" alt="'+elem.alt+'">';
}

Categories

Resources