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

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);
});
}

Related

PDF.JS only updates every other time

I'm trying to implement a "drag-to-pan" function for the pfd.js viewer.
However, this only works every other time, so that after panning around, I have to click the viewer again to make it re-render.
Here's the code:
var pdfScale = 1;
var activePdf;
var rotate = 0;
var addX = 0;
var addY = 0;
function renderPage(page) {
activePdf = page;
var canvas = document.getElementById('the-canvas');
var wrapperStyle = window.getComputedStyle(document.getElementsByClassName("canvas-wrapper")[0]);
var context = canvas.getContext('2d');
var viewport = page.getViewport(pdfScale, rotate);
canvas.height = parseInt(wrapperStyle.height);
canvas.width = parseInt(wrapperStyle.width);
viewport.viewBox[0] -= addX;
viewport.viewBox[2] -= addX;
viewport.viewBox[1] += addY;
viewport.viewBox[3] += addY;
addX = addY = 0;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
}
$(document).ready(function() {
var start = [0,0];
$('#the-canvas').mousedown(function(event) {
start[0] = event.screenX;
start[1] = event.screenY;
}).mouseup(function(event) {
console.log(event);
addX = event.screenX - start[0];
addY = event.screenY - start[1];
setTimeout(function() {
renderPage(activePdf);
}, 500);
});
var url = 'http://localhost/test.pdf';
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
PDFJS.disableWorker = true;
// The workerSrc property shall be specified.
PDFJS.workerSrc = 'build/pdf.worker.js';
// Asynchronous download of PDF
var loadingTask = PDFJS.getDocument(url);
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
renderPage(page);
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
});
Even after adding the setTimeout, it still doesn't render correctly on the first time. How can I edit my logic to make it work?
Thanks!

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.

Can't limit number of files and save it to database, Image uploader Javascript and PHP

first of all Im really new with Javascript and lets tell you what i need.
I have this code to make an image uploader to resize it on client-side and works perfect, made by Joel Vardy. But I need to limint the number of images to upload by 10. I can't figured it out how to do it... also i can't find a way to host the image links on the Database via php
The HTML
<head>
<title>Upload Photos</title>
<link rel="stylesheet" href="./style.css" />
<head>
<body>
<h1>Upload Photos</h1>
<form>
<input type="file" accept="image/*" multiple />
<div class="photos">
</div>
</form>
<script src="./upload.js"></script>
</body>
The JS
document.querySelector('form input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
// Iterate through files
for (var i = 0; i < files.length; i++) {
// Ensure it's an image
if (files[i].type.match(/image.*/)) {
// Load image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Add elemnt to page
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
// Resize image
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
// Upload image
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
// File uploaded / failed
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
// Start upload
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
// Clear files
event.target.value = '';
});
The PHP
$filename = md5(mt_rand()).'.jpg';
$data = file_get_contents('php://input');
$image = file_get_contents('data://'.substr($data, 5));
if ( ! file_put_contents('images/'.$filename, $image)) {
header('HTTP/1.1 503 Service Unavailable');
exit();
}
unset($data);
unset($image);
echo './images/'.$filename;
Any help will be appreciated, Thank you!
To limit the script to only work with max 10 files, do something like this:
for (var i = 0; i < files.length; i++) {
if (i < 11){
}
}
for the database, read about mysql and learn it.

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();">

Image() onLoad not waiting for image to load

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>

Categories