Image() onLoad not waiting for image to load - javascript

I've figured out the centering and resizing issues, but I still can't get onLoad to work properly. Anyone have any ideas? I thought onLoad was supposed to wait for the image to be loaded completely before firing the code. As this is right now, it resizes the img for the next img, and fades it in before it's loaded, so the previous image fades in again. Once the show has run through once, it works perfectly, so obviously it's not waiting for the image to load completely before firing imageLoad().
<div id="slideShow">
<div id="slideShowImg" style="display:none; margin-right:auto; margin-left:auto;">
</div>
<div id="slideShowThumbs">
</div>
<script type="text/javascript">
loadXMLDoc('http://www.thehoppr.com/hopspots/82/82.xml', function() {
var slideShow = document.getElementById('slideShow');
var items = [];
var nl = xmlhttp.responseXML.getElementsByTagName('image');
var i = 0;
var t;
var slideShowImg = document.getElementById('slideShowImg');
var slideShow = document.getElementById('slideShow');
var maxHeight = 300;
var maxWidth = 800;
var imgNode = new Image();
function image() {
var nli = nl.item(i);
var src = nli.getAttribute('src').toString();
var width = parseInt(nli.getAttribute('width').toString());
var height = parseInt(nli.getAttribute('height').toString());
imgNode.onLoad = imageLoad();
imgNode.src = src;
imgNode.height = height;
imgNode.width = width;
imgNode.setAttribute("style", "margin-right:auto; margin-left:auto; display:block;");
var ratio = maxHeight / maxWidth;
if (imgNode.height / imgNode.width > ratio) {
// height is the problem
if (imgNode.height > maxHeight) {
imgNode.width = Math.round(imgNode.width * (maxHeight / imgNode.height));
imgNode.height = maxHeight;
}
} else {
// width is the problem
if (imgNode.width > maxHeight) {
imgNode.height = Math.round(imgNode.height * (maxWidth / imgNode.width));
imgNode.width = maxWidth;
}
}
}
function imageLoad() {
slideShowImg.appendChild(imgNode);
Effect.Appear('slideShowImg', {
duration: 1
});
t = setTimeout(nextImage, 7000);
}
function nextImage() {
slideShowImg.setAttribute("style", "display:none");
if (i < nl.length - 1) {
i++;
image();
} else {
i = 0;
image();
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//XML Loaded, create the slideshow
alert(xmlhttp.responseText);
image();
}
});
</script>

Here are some of my thoughts (it's all open discussion)...
Preloading - Since you're limited to downloading 2 resources in parallel per hostname, it may not make sense to preload everything up front. Since it's a slideshow, how about modifying image() to download the i + 1 image through an Image object that doesn't get appended to the DOM? It doesn't seem beneficial to prefetch i + 2 and beyond in a slideshow setting.
Centering the images - Regarding using the auto margin width for horizontal centering, I believe you'll have to explicitly set the image to display:block. Obviously that doesn't solve centering vertically. Are all the images the same size? Also, will the slideShowImg div have a defined height/width? If so, then some math can be applied to achieve the centering.
Hope this helps! :)

Ok so I fixed the issue with the onLoad, and I even added a little preloading to help the slideshow along as well. All I had to do was define the onload first, and then do everything else except define the src inside the onload's function. I then added a little nextImg preloading so there's little if no hiccup between images even if it's the first time the browser is loading them. Here's the final code for anyone who has similar onload issues and finds there way here:
<div id="slideShow">
<div id="slideShowImg" style="display:none; margin-right:auto; margin-left:auto;">
</div>
<div id="slideShowThumbs">
</div>
<script type="text/javascript">
loadXMLDoc('/82.xml', function() {
var slideShow = document.getElementById('slideShow');
var items = [];
var nl = xmlhttp.responseXML.getElementsByTagName('image');
var i = 0;
var t;
var slideShowImg = document.getElementById('slideShowImg');
var slideShow = document.getElementById('slideShow');
var maxHeight = 300;
var maxWidth = 800;
var curImg = new Image();
var nextImg = new Image();
function image() {
var cli = nl.item(i);
var src = cli.getAttribute('src').toString();
var width = parseInt(cli.getAttribute('width').toString());
var height = parseInt(cli.getAttribute('height').toString());
curImg.onload = function() {
curImg.height = height;
curImg.width = width;
curImg.setAttribute("style", "margin-right:auto; margin-left:auto; display:block;");
slideShowImg.appendChild(curImg);
var ratio = maxHeight / maxWidth;
if (curImg.height / curImg.width > ratio) {
// height is the problem
if (curImg.height > maxHeight) {
curImg.width = Math.round(curImg.width * (maxHeight / curImg.height));
curImg.height = maxHeight;
}
} else {
// width is the problem
if (curImg.width > maxHeight) {
curImg.height = Math.round(curImg.height * (maxWidth / curImg.width));
curImg.width = maxWidth;
}
}
}
curImg.src = src;
if (i < nl.length - 1) {
var nli = nl.item(i + 1);
var nsrc = nli.getAttribute('src').toString();
nextImg.src = nsrc;
}
Effect.Appear('slideShowImg', {
duration: 1
});
t = setTimeout(nextImage, 7000);
}
function imageLoad() {}
function nextImage() {
slideShowImg.removeChild(curImg);
slideShowImg.setAttribute("style", "display:none");
if (i < nl.length - 1) {
i++;
image();
} else {
i = 0;
image();
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//XML Loaded, create the slideshow
alert(xmlhttp.responseText);
image();
}
});
</script>

Related

javascript slideshow sometimes messes up

This one is driving me crazy. My javascript code works for most slides in a deck I create but sometimes it messes up. It usually takes one of four forms:
the slide will appear as a tiny picture under a logo I put on the slide when the slide isn't wide enough to fill the viewing area, or
the slide will appear properly sized but under the logo which now occupies the full height of the viewing area, or
both of the above, or
neither the slide nor the logo appear. Instead the previous slide continues to be shown.
My code isn't all that complicated. The part that shows the individual slide is below:
var backgroundImage;
var imgHeight;
var imgWidth;
function waitForHeight() {
sleep(120).then(() => {
if (imgHeight == 0) {
waitForHeight()
} else {
setBackground();
}
});
}
function getSizes() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = getSizes;
myImage.src = imgPath;
return myImage;
}
function setBackground() {
var backgroundPosition = "";
var backgroundSize = "100%";
var aspectRatio = imgHeight / imgWidth;
if (aspectRatio > 0.70) {
backgroundSize = "10vw, auto 100%";
backgroundImage = "URL(images/LCI_emblem_2color.png), " + backgroundImage;
backgroundPosition = "top 1rem left 1rem, top right";
}
var mainPanel = document.getElementById("mainpanel")
mainPanel.style.backgroundImage = backgroundImage;
mainPanel.style.backgroundPosition = backgroundPosition;
mainPanel.style.backgroundSize = backgroundSize;
}
function addPic(curCell, curSlide, nodeNum) {
imgHeight = 0; // flag that height not set yet
var curImg = showImage(curSlide.childNodes[nodeNum].firstChild.nodeValue);
curImg.setAttribute('class', 'd-none d-md-block');
curCell.appendChild(curImg);
backgroundImage = "URL(" + getSlidePicture(curSlide) + ")";
waitForHeight();
}
The code, as I said, is not complicated. I can understand somewhat what the problem is - either the picture doesn't load or it gets put into the wrong "background" area, but I don't get why it happens.
I've noted the issue occurs with the same slides in both Chromium and Firefox and has survived multiple versions of each browser, so it's probably not a browser issue.
Any ideas?

why this javascript code don't work after i reload part of my page with ajax?

I have 3 files with php and js. in first file i load some information and show it to user, then user can change them. for show other information to user i reload part of my page with some code that they are in second php file. i put them in <div id='show_album'>my data</div> and change them with second php file.
for first run my javascript code work fine, but after reloading part of page it never work. what must i change in code that it work after reloading?!
this is part of code that can reload div element with ajax:
<select onchange="showList('showalbum.php?change=',this.value,'show_album')"><option value='1'>1</option> <option value='2'>2</option></select>
in this part of code that in first page i reload my div element with new data.
then in new data i have something like this:
size of picture: 460*345
that show picture link to user and when user click on it, with javascript i show it to user on this page and on my other information that user can close it.but now this rel="lightbox" don't work and when user click on link, this picture open in same window.
this is my javascript code and in <head> i define it:
/*
Table of Contents
-----------------
Configuration
Functions
- getPageScroll()
- getPageSize()
- pause()
- getKey()
- listenKey()
- showLightbox()
- hideLightbox()
- initLightbox()
- addLoadEvent()
Function Calls
- addLoadEvent(initLightbox)
*/
//
// Configuration
//
// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = './LightBox/loading.gif';
var closeButton = './LightBox/close.gif';
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
arrayPageScroll = new Array('',yScroll)
return arrayPageScroll;
}
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = document.body.scrollWidth;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
}
//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if(key == 'x'){ hideLightbox(); }
}
//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }
//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
// prep objects
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objCaption = document.getElementById('lightboxCaption');
var objImage = document.getElementById('lightboxImage');
var objLoadingImage = document.getElementById('loadingImage');
var objLightboxDetails = document.getElementById('lightboxDetails');
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
// center loadingImage if it exists
if (objLoadingImage) {
objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
objLoadingImage.style.display = 'block';
}
// set height of Overlay to take up whole page and show
objOverlay.style.height = (arrayPageSize[1] + 'px');
objOverlay.style.display = 'block';
// preload image
imgPreload = new Image();
imgPreload.onload=function(){
objImage.src = objLink.href;
// center lightbox and make sure that the top and left values are not negative
// and the image placed outside the viewport
var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
objLightboxDetails.style.width = imgPreload.width + 'px';
if(objLink.getAttribute('title')){
objCaption.style.display = 'block';
//objCaption.style.width = imgPreload.width + 'px';
objCaption.innerHTML = objLink.getAttribute('title');
} else {
objCaption.style.display = 'none';
}
// A small pause between the image loading and displaying is required with IE,
// this prevents the previous image displaying for a short burst causing flicker.
if (navigator.appVersion.indexOf("MSIE")!=-1){
pause(250);
}
if (objLoadingImage) { objLoadingImage.style.display = 'none'; }
objLightbox.style.display = 'block';
// After image is loaded, update the overlay height as the new image might have
// increased the overall page height.
arrayPageSize = getPageSize();
objOverlay.style.height = (arrayPageSize[1] + 'px');
// Check for 'x' keypress
listenKey();
return false;
}
imgPreload.src = objLink.href;
var e = document.getElementById('gand');
e.style.display = 'none';
}
//
// hideLightbox()
//
function hideLightbox()
{
// get objects
objOverlay = document.getElementById('overlay');
objLightbox = document.getElementById('lightbox');
// hide lightbox and overlay
objOverlay.style.display = 'none';
objLightbox.style.display = 'none';
// disable keypress listener
document.onkeypress = '';
var e = document.getElementById('gand');
e.style.display = 'block';
}
//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName("a");
// loop through all anchor tags
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
anchor.onclick = function () {showLightbox(this); return false;}
}
}
// the rest of this code inserts html at the top of the page that looks like this:
//
// <div id="overlay">
// <img id="loadingImage" />
// </div>
// <div id="lightbox">
// <a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
// <img id="closeButton" />
// <img id="lightboxImage" />
// </a>
// <div id="lightboxDetails">
// <div id="lightboxCaption"></div>
// <div id="keyboardMsg"></div>
// </div>
// </div>
var objBody = document.getElementsByTagName("body").item(0);
// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.onclick = function () {hideLightbox(); return false;}
objOverlay.style.display = 'none';
objOverlay.style.position = 'absolute';
objOverlay.style.top = '0';
objOverlay.style.left = '0';
objOverlay.style.zIndex = '90';
objOverlay.style.width = '100%';
objBody.insertBefore(objOverlay, objBody.firstChild);
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
// preload and create loader image
var imgPreloader = new Image();
// if loader image found, create link to hide lightbox and create loadingimage
imgPreloader.onload=function(){
var objLoadingImageLink = document.createElement("a");
objLoadingImageLink.setAttribute('href','#');
objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
objOverlay.appendChild(objLoadingImageLink);
var objLoadingImage = document.createElement("img");
objLoadingImage.src = loadingImage;
objLoadingImage.setAttribute('id','loadingImage');
objLoadingImage.style.position = 'absolute';
objLoadingImage.style.zIndex = '150';
objLoadingImageLink.appendChild(objLoadingImage);
imgPreloader.onload=function(){}; // clear onLoad, as IE will flip out w/animated gifs
return false;
}
imgPreloader.src = loadingImage;
// create lightbox div, same note about styles as above
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.style.position = 'absolute';
objLightbox.style.zIndex = '100';
objBody.insertBefore(objLightbox, objOverlay.nextSibling);
// create link
var objLink = document.createElement("a");
objLink.setAttribute('href','#');
objLink.setAttribute('title','براي بستن کليک کنيد');
objLink.onclick = function () {hideLightbox(); return false;}
objLightbox.appendChild(objLink);
// preload and create close button image
var imgPreloadCloseButton = new Image();
// if close button image found,
imgPreloadCloseButton.onload=function(){
var objCloseButton = document.createElement("img");
objCloseButton.src = closeButton;
objCloseButton.setAttribute('id','closeButton');
objCloseButton.style.position = 'absolute';
objCloseButton.style.zIndex = '200';
objLink.appendChild(objCloseButton);
return false;
}
imgPreloadCloseButton.src = closeButton;
// create image
var objImage = document.createElement("img");
objImage.setAttribute('id','lightboxImage');
objLink.appendChild(objImage);
// create details div, a container for the caption and keyboard message
var objLightboxDetails = document.createElement("div");
objLightboxDetails.setAttribute('id','lightboxDetails');
objLightbox.appendChild(objLightboxDetails);
// create caption
var objCaption = document.createElement("div");
objCaption.setAttribute('id','lightboxCaption');
objCaption.style.display = 'none';
objLightboxDetails.appendChild(objCaption);
// create keyboard message
var objKeyboardMsg = document.createElement("div");
objKeyboardMsg.setAttribute('id','keyboardMsg');
objKeyboardMsg.innerHTML = 'براي بستن کليد <kbd>x</kbd> را فشار دهيد';
objLightboxDetails.appendChild(objKeyboardMsg);
}
//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(initLightbox); // run initLightbox onLoad
and i have css for this js that it is not importat but i write it here:
#lightbox {
background-color: #eee;
padding: 10px;
border-bottom: 2px solid #666;
border-right: 2px solid #666;
}
#lightboxDetails {
font-size: 0.8em;
padding-top: 0.4em;
}
#lightboxCaption {
float: left;
}
#keyboardMsg {
float: right;
}
#closeButton {
top: 5px;
right: 5px;
}
#lightbox img {
border: none;
clear: both;
}
#overlay img {
border: none;
}
#overlay {
background: url(../LightBox/overlay.png);
}
* html #overlay {
background-color: #000;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="../LightBox/overlay.png", sizingMethod="scale");
filter: alpha(opacity=70);
opacity: 0.7;
}
i think this code just run one time on window.load() and after i reload part of page it can't load again and don't work.
how i can resolve this problem?
tnks for reading my question...
Because to new html elements added after you need to recall all functions that work with it, for example recall functions that is called on document is created
When you get result from ajax and put it on html page, after write initLightbox();
You need to add initLightbox() here and change them with second php file. for first run my javascript
But you not write that code and I can't help you.
I can say only, put initlightbox after code where you receive response with ajax after lines where you insert new html elements.

how to implement automatic sliding images through array in javascript

I want to implement sliding images as soon as the website loads.
Here's my html code
<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>
And here's my javascript
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{ x=x+1
if(x>4)
x=1
document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
var t=setInterval("images()",3000);
}
Help will be appreciated.
Although you mentioned "sliding" your initial code looked liked you wanted to swap the images over time.
I admit you may struggle to find good resources on JavaScript for something so simple, which Is why I can relate to your question.
Ok so here's a quick & dirty but more modern-ish image changing slide requestAnimationFrame:
https://jsfiddle.net/julienetienne/95tqftnk/4/
The same principals apply for making images slide except you are pre-loading all images and shifting the position by the slide show width.
var speed = 3;
// Your image array
var images = [
'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];
// Get the slideShow tag
var slideShow = document.getElementById('slide-show');
// Create the image tag //You could also just make one in HTML and get the tag
var img = document.createElement('img');
// Append the image to the slideshow container
slideShow.appendChild(img);
// Basic request animation polyfill
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
return setTimeout(callback, 1000 / 60);
};
// declare var count outside of rAF loop
var count;
function changeImage(timeStamp) {
count = Math.floor(timeStamp / 1000 / speed);
while (count > images.length -1) {
count -= images.length;
}
img.src = images[count];
rAF(changeImage);
}
rAF(changeImage);
img {
width: 600px;
height auto;
}
<div id="slide-show"></div>

Javascript Image resizing is not working properly in IE11 but working in remaing versions(10,9,8)

I am using wicket framework (html +java) in my application where i need to resize an image when the componenet loads.This code is working fine in IE8,9,10.But it is failing sometimes in IE11.
Some times it is able to resize and but sometimes it is not able to do so.Actully it is not going into the javascript code whenver it fails.
Please help me in solving the issue.
<img wicket:id="bigImage" onload="resize_imgs(140,140,112,112)" />
Here the above image compnenet is calling following javascript code and will perfrom the image resizing.
<script type="text/javascript">
function resize_imgs(maxht, maxwt, minht, minwt) {
alert("first line");
var imgs = document.getElementsByTagName('img');
var resize_img = function (img, newht, newwt) {
img.height = newht;
img.width = newwt;
alert("in resize image function :newht" + newht + "newwt:" + newwt);
};
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
if (img.height > maxht || img.width > maxwt) {
var old_ratio = img.height / img.width;
var min_ratio = minht / minwt;
if (old_ratio === min_ratio) {
alert("ratios equal");
resize_img(img, minht, minwt);
}
else {
var newdim = [img.height, img.width];
newdim[0] = minht;
newdim[1] = newdim[0] / old_ratio;
if (newdim[1] > maxwt) {
newdim[1] = minwt;
newdim[0] = newdim[1] * old_ratio;
}
alert("ratios not equal");
resize_img(img, newdim[0], newdim[1]);
}
}
}
}
</script>
UPDATE1:
In my appllication there are lot of images in a page and when we click on image or opens that page it will take first image or clicked image and will set it in top corner of the page.So whenever that component loads (img wicket:id="bigImage" onload="resize_imgs(140,140,112,112)" /> )we will call onload event.Now i have been trying with jquery.I updated it in the question.Could you please suggest me whether it is correct or not.
<img class="resizeImage" wicket:id="bigImage" />
$(document).ready(function(){
$(".resizeImage").one("load", function() {
// do stuff
var maxht=140;
var maxwt =140;
var minht=112;
var minwt=112;
var img_height = $(this).height();
var img_width = $(this).width();
if (img_height > maxht || img_width > maxwt) {
var old_ratio = img_height / img_width;
var min_ratio = minht / minwt;
if (old_ratio === min_ratio) {
$(this).css('height',minht);
$(this).css('width',minwt);
}
else {
var newdim = [img_height, img_width];
newdim[0] = minht;
newdim[1] = newdim[0] / old_ratio;
if (newdim[1] > maxwt) {
newdim[1] = minwt;
newdim[0] = newdim[1] * old_ratio;
}
$(this).css('height',newdim[0]);
$(this).css('width',newdim[1]);
}
}}).each(function() {
if(this.complete) $(this).load();
});
If the image can be pulled from the cache immediately, then IE won't trigger the load event for the image at all.
You can check if the complete property of the image is true. Then the image is already loaded and you won't get a load event, so you can just call the function directly. Example:
var image = $('img');
if (image.prop('complete')) {
resize_imgs(140,140,112,112);
} else {
image.load(function(){
resize_imgs(140,140,112,112);
});
}

JS OnLoad Images Not Being Resized

So I am sure I am missing something small here. I wrote this awhile ago but I came back to it the other day to try and remember why I stopped working on it. Then I realized it's because when you load the page for the first time it doesn't resize the images in the image gallery container.
Then on page refresh the images resize themselves the way they are supposed to. Here is the code.
var ImageGallery = (function(){
/*
Load Images expects an array of URLS for your images, then
it returns an array of new images.
*/
function loadImages(urls){
var images = [];
for(i = 0; i < urls.length; i++){
var tempImage = new Image();
tempImage.src = urls[i];
tempImage.className = "slider-images";
var image = scaleImage(tempImage, 100,100);
//adds even listener to each image
image.addEventListener('click', function(){
addMainPicture(this);
}, false);
images.push(image);
}
var imageContainer = document.getElementById("image-container");
for(i = 0; i < images.length; i++){
imageContainer.appendChild(images[i]);
}
//add main picture
var temp = new Image();
temp.src = urls[0];
temp.className = "slider-images";
var tempMainImage = scaleImage(temp,350,350);
console.log(tempMainImage);
addMainPicture(tempMainImage);
}
/*
Adds the Main Picture. In here you can set the size you want the image
to be, and other styling for the image. Takes in the url for the image.
*/
function addMainPicture(image){
var mainPicture = document.getElementById("main-picture");
mainPicture.src = image.src;
//add styles
mainPicture.style.display = "block";
mainPicture.style.margin = "0px auto";
}
/*
Scales the image taken in to the maxWidth, and maxHeight
stated.Only scales down. Not up.
*/
function scaleImage(img, maxW, maxH){
var maxWidth = maxW,
maxHeight = maxH,
ratio = 0,
imgWidth = img.width,
imgHeight = img.height;
//check width
if(imgWidth > maxWidth){
ratio = maxWidth / imgWidth;
img.width = maxWidth;
img.height = imgHeight * ratio;
imgHeight = imgHeight * ratio;
imgWidth = imgWidth * ratio;
}
//check height
if(imgHeight > maxHeight){
ratio = maxHeight / imgHeight;
img.height = maxHeight;
img.width = maxWidth;
imgWidth = imgWidth * ratio;
}
return img;
}
/*
This runs it all.
*/
function init(){
var urls = ["http://placehold.it/400x400","http://placehold.it/400x400/FFF000","http://placehold.it/400x400/FF0000","http://placehold.it/400x400/0000FF"];
//load in urls for images
loadImages(urls);
var leftButton = document.getElementById("scroll-left"),
rightButton = document.getElementById("scroll-right");
leftButton.addEventListener('click', function(){
var imageContainer = document.getElementById("image-container");
var currentLeft = "";
//checks for NaN
if(imageContainer.style.left == ""){
currentLeft = 0;
}else{
currentLeft = parseInt(imageContainer.style.left);
}
var end = currentLeft + 300;
function frame(){
currentLeft+=5;
imageContainer.style.left = currentLeft+"px";
if(currentLeft == end)
clearInterval(id);
}
var id = setInterval(frame, 10);
}, false);
rightButton.addEventListener('click', function(){
var imageContainer = document.getElementById("image-container");
var currentLeft = "";
if(imageContainer.style.left == ""){
currentLeft = 0;
}else{
currentLeft = parseInt(imageContainer.style.left);
}
var end = currentLeft - 300;
function frame(){
currentLeft-=5;
imageContainer.style.left = currentLeft+"px";
if(currentLeft == end)
clearInterval(id);
}
var id = setInterval(frame, 10);
}, false);
}
return {
init: function(){
init();
}
}
}());
ImageGallery.init();
Sure I am missing something small here but would really like another set of eyes on it.
Here is the fiddle.
Use onLoad event for images. Because your images are not loaded and you need to load images first to scale them:-
tempImage.onload = function(){
scaleImage(this, 100,100);//here your scale code goes
}
You need to run ImageGallery.init(); once the document has loaded, with jQuery you would use:
$(function() {
ImageGallery.init();
});
Without jQuery, you can use
<body onload="ImageGallery.init();">

Categories