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

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.

Related

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

Javascript: move new element after createElement

I have created a zombie img in my banner div but I can't get the img to move to the left after it has been created.
createZombie function is on a timer:
createZombieTimer = window.setInterval(createZombie, 1000);
That is in an init() that loads with the body.
function createZombie(){
var imgElem = document.createElement("img");
imgElem.src = "img/zombie_walk_right.gif";
var newZom = document.getElementById('banner').appendChild(imgElem);
newZom.style.height = "40px";
newZom.style.width = "auto";
newZom.style.display = "block";
newZom.style.marginLeft = "50px";
var zomPos = parseInt(newZom.style.marginLeft);
if (zomPos > 0) {
newZom.style.marginLeft = (zomPos + 50) + "px";
}
}
Since it's clear from the comments now what you want to do, I'll post it here as the answer.
You can do this with plain javascript as well. What you will have to do, is use setInterval(). This will execute a function every second, in which you can update the position of the elements.
Example:
// Function to move the zombie by 50 pixels
function moveZombie()
{
// Select the zombie element (will need additional logic to select all of them, just an example)
zomElement = document.getElementById('zombie1');
zomPos = parseInt(zomElement.style.marginLeft);
zomElement.style.marginLeft = (zomPos + 50) + 'px';
}
// Call this function every second
setInterval(moveZombie(), 1000);

adding text to overlay in javascript

I've used some source for a transparent overlay in JavaScript:
function grayOut(vis, options)
{
var options = options || {};
var zindex = 50;
var opacity = 70;
var opaque = (opacity / 100);
var bgcolor = options.bgcolor || '#000000';
var dark=document.getElementById('darkenScreenObject');
if (!dark) {
// The dark layer doesn't exist, it's never been created. So we'll
// create it here and apply some basic styles.
// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
var tbody = document.getElementsByTagName("body")[0];
var tnode = document.createElement('div'); // Create the layer.
tnode.style.position='absolute'; // Position absolutely
tnode.style.top='0px'; // In the top
tnode.style.left='0px'; // Left corner of the page
tnode.style.display='none'; // Start out Hidden
tnode.id='darkenScreenObject'; // Name it so we can find it later
tbody.appendChild(tnode);
/*
var pTag = document.createElement("P");
var txtProcessing = document.createTextNode("Processing GIF...");
tnode.appendChild(txtProcessing);
*/
}
if (vis)
{
// Calculate the page width and height
if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
{
var pageWidth = document.body.scrollWidth+'px';
var pageHeight = document.body.scrollHeight+'px';
}
else if( document.body.offsetWidth )
{
var pageWidth = document.body.offsetWidth+'px';
var pageHeight = document.body.offsetHeight+'px';
}
else
{
var pageWidth='100%';
var pageHeight='100%';
}
//set the shader to cover the entire page and make it visible.
dark.style.opacity=opaque;
dark.style.MozOpacity=opaque;
dark.style.filter='alpha(opacity='+opacity+')';
dark.style.zIndex=zindex;
dark.style.backgroundColor=bgcolor;
dark.style.width= pageWidth;
dark.style.height= pageHeight;
dark.style.display='block';
var txt = document.createTextNode("This text was added.");
dark.appendChild(txt);
}
else
{
dark.style.display='none';
}
}
My problem is I'm trying to get some text to show up on the transparent layer but I can't get it to work. Any thoughts?
Your text node is created on overlay but is invisible cause of text color.
check Fiddle where text color is set to red.
dark.style.color = 'red';

Replace the end of a File Name (SRC)

i'm having a bit of a problem here. I found this script on the web, and changed it around a bit for my needs.
This script shows a preview of the image following the mouse onmouseover.
Originally, there was only one way of doing this. But i have 2 different sections on my website in which i want to display images with different attributes (height, width).
I was able to do that, the problem is that on the second section, the src (file name) is a thumbnail of the actual picture i want to display, so when it dows, it just blows up a very small picture, which looks very bad. But hopefully, this will make things easier: all the thumbnails are named whaterver_small.jpg and the originals, whatever.jpg Now, if i could remove _small or _small.jpg and replace with .jpg from the end of that file, that would display the original picture for me, which would be great. This is how the funcion is called on html:
Original size, no need changing:
<a href=http://www.whatever.net/1.html');">
<img alt="Copper" border="1" height="64" src="http://www.whatever.net/whatever_small.jpg" width="85" onmouseover="showImage1(this.src,this,'Whatever')" /></a>
Show image2, the one i'm having problems with.
<a href=http://www.whatever.net/1.html');">
<img alt="Copper" border="1" height="64" src="http://www.whatever.net/whatever_small.jpg" width="85" onmouseover="showImage2(this.src,this,'Whatever')" /></a>
This is the script
var floatWidth = 150; // set the width of the floating image
var floatHeight = 100; // set its height
var floatWidth2 = 320; // set the width of the floating image
var floatHeight2 = 240; // set its height
var midWindow = 0;
var nContainer = "";
var IE = false;
if (navigator.appName == 'Microsoft Internet Explorer'){IE = true}
function stayHome(m){
if (IE)
{
var currX = event.clientX;
var currY = event.clientY;
}
else {
var currX = m.pageX;
var currY = m.pageY;
}
if (document.documentElement && document.documentElement.scrollLeft || document.documentElement && document.documentElement.scrollTop)
{
var iL = document.documentElement.scrollLeft;
var iV = document.documentElement.scrollTop;
}
else {
var iL = document.body.scrollLeft;
var iV = document.body.scrollTop;
}
if (currX > midWindow+80)
{
var msgWidth = nContainer.clientWidth;
if (IE){nContainer.style.left = (currX-msgWidth-10+iL)+'px'}
else {nContainer.style.left = (currX-msgWidth-10)+'px'}
}
else {
if (IE){nContainer.style.left = (currX+15+iL)+'px'}
else {nContainer.style.left = (currX+15)+'px'}
}
if (IE){nContainer.style.top = (currY+iV-(floatHeight/2)+70)+'px'}
else {nContainer.style.top = (currY-(floatHeight/2)+70)+'px'}
}
function hideImage(){
while (nContainer.lastChild)
{nContainer.removeChild(nContainer.lastChild)}
document.getElementById('isFloat').style.display = 'none';
}
function showImage(isImg,currItem,currCaption){
document.getElementById('isFloat').style.display = 'inline';
nIMG = document.createElement('img');
nContainer.appendChild(nIMG);
nIMG.setAttribute('src',isImg);
nIMG.setAttribute('width',floatWidth);
nIMG.setAttribute('height',floatHeight);
nCaption = document.createElement('div');
nCaption.style.textAlign = "center";
nCaption.style.backgroundColor = '#EAE3C6';
nCaption.style.padding = '5px';
nCaption.style.color = '#000000';
nCaption.style.fontFamily = 'Sans-serif';
nCaption.style.fontSize = '10pt';
nCaption.style.borderTop = "1px solid black";
nContainer.appendChild(nCaption);
nCaption.innerHTML = currCaption;
currItem.onmouseout=hideImage;
}
function showImage2(isImg,currItem,currCaption){
document.getElementById('isFloat').style.display = 'inline';
nIMG = document.createElement('img');
nContainer.appendChild(nIMG);
nIMG.setAttribute('src',isImg);
nIMG.setAttribute('width',floatWidth2);
nIMG.setAttribute('height',floatHeight2);
nCaption = document.createElement('div');
nCaption.style.textAlign = "center";
nCaption.style.backgroundColor = '#EAE3C6';
nCaption.style.padding = '5px';
nCaption.style.color = '#000000';
nCaption.style.fontFamily = 'Sans-serif';
nCaption.style.fontSize = '10pt';
nCaption.style.borderTop = "1px solid black";
nContainer.appendChild(nCaption);
nCaption.innerHTML = currCaption;
currItem.onmouseout=hideImage;
}
function getMidWindow(){
if (document.documentElement && document.documentElement.scrollLeft || document.documentElement && document.documentElement.scrollTop)
{
midWindow = document.documentElement.clientWidth/2;
}
else {
midWindow = document.body.clientWidth/2;
}
}
function initFloatImg(){
var nBody = document.getElementsByTagName('body')[0];
var nDiv = document.createElement('div');
nDiv.id = "isFloat";
nDiv.style.position = "absolute";
nDiv.style.top = "0px";
nDiv.style.left = "0px";
nDiv.style.border = "1px solid black";
nDiv.style.padding = "5px";
nDiv.style.backgroundColor = "#ffffff"
nBody.appendChild(nDiv);
nContainer = document.getElementById('isFloat');
document.onmousemove = stayHome;
hideImage();
if (!IE){document.captureEvents(Event.mousemove)}
getMidWindow();
}
onload=initFloatImg;
onresize=getMidWindow;
Update:
Ok, so i updated the script in this page, and it works perfectly now.
I ran into another problem, when the picture that has the mouse over, is near the end of the page, the preview is cutoff. I'd like to be able to move the preview up, so there's no scroll bar.
Here's a live example of a functional one: http://www.soccer.com/Navigation.process?Ne=178&N=4294960224+346
Where the picture is never cutoff.
Replace following line in the showImage2 function
nIMG.setAttribute('src',isImg);
with
nIMG.setAttribute('src',isImg.replace(/_small\./, '.'));
This will remove all _small matches from all of your image sources, if I'm understanding what you want correctly:
$("img").each(function() {
$(this).attr("src", $(this).attr("src").replace("/_small(?=\.)/", ""));
});

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