img onclick fire js function only second click - javascript

On html page I have several images with <img onclick="povecaj();"
In fact, trying to make some kind of light-box.
First img click not work, second click fired function and any other img first click fired function. But after page loaded fist img click doesn't work...
function is next:
function povecaj() {
if (document.readyState === "complete") {
if ((screen.width > 801) || (screen.height > 801)) {
init();
}
else {
return;
}
}
}
function init() {
$(' .card-img img').click(function () {
var thediv = document.getElementById('displaybox');
var staza = $(this).attr('src')
var sl = document.getElementById('image');
thediv.style.display = "";
sl.innerHTML = '<img alt="2" id="imgID" src="' + staza + '"/>' + '<div class="alert-close" onclick = "zapri()" >X</div>'
thediv.innerHTML = '<table style="width:100%; height:100%;"><tbody><tr><td style="text-align: center; vertical-align:central; width:100%; height:100%"></td></tr></tbody></table>';
thediv.style.display = "block";
sl.style = "block";
});
}
I'm working in VS2012, using Chrome inspect too.. can't see errors..
searched, googled, can't find solution. Can somebody help?

If your images loading dynamically the DOM you must add a jquery event listener like this:
function init() {
$(class_of_parent_div).on('click', '.card-img img', function () {
var thediv = document.getElementById('displaybox');
var staza = $(this).attr('src')
var sl = document.getElementById('image');
thediv.style.display = "";
sl.innerHTML = '<img alt="2" id="imgID" src="' + staza + '"/>' + '<div class="alert-close" onclick = "zapri()" >X</div>'
thediv.innerHTML = '<table style="width:100%; height:100%;"><tbody><tr><td style="text-align: center; vertical-align:central; width:100%; height:100%"></td></tr></tbody></table>';
thediv.style.display = "block";
sl.style = "block";
});
}
And write the class of parent div class_of_parent_div

Related

show child element right after implementation

var firstMove = 0;
var pictures = ['boar.jpg','lion.jpg','bones.jpg','eagle.jpg','wolf.jpg','boar.jpg','lion.jpg','bones.jpg','eagle.jpg','wolf.jpg','boar.jpg','lion.jpg','bones.jpg','eagle.jpg','wolf.jpg']
pictures.sort()
function replyClick(clicked_id)
{
//if player already draw one card;
if (firstMove){
var image = document.getElementById(clicked_id);
image.innerHTML = '<img src='+pictures[clicked_id-1]+' />'
var firstPicture = document.getElementById(firstMove);
if (image.innerHTML == firstPicture.innerHTML){
firstMove=0;
}
else {
image.innerHTML = "";
firstPicture.innerHTML = "";
firstMove=0
}
}
// if player didnt draw any card;
else {
var image = document.getElementById(clicked_id);
image.innerHTML = '<img src='+pictures[clicked_id-1]+' />'
firstMove = clicked_id
}
}
<div class="card" id="1" onclick="replyClick(this.id)"></div>
<div class="card" id="2" onclick="replyClick(this.id)"></div>
I try to create simple pexeso game.where you looking for two identical images.
My question is how to change this code to show that certain image right after somebody click on it.Because my script show image after inner condition but that is too late for me.Thanks for answer
Compare array elements.
pictures[clicked_id-1] == pictures[firstMove-1]
is the same that
image.innerHTML == firstPicture.innerHTML
UPD
For small delay use setTimeout
// other code
function replyClick(clicked_id) {
if (firstMove){
var imageSrc = pictures[clicked_id-1];
var prevImageSrc = pictures[firstMove-1];
var image = document.getElementById(clicked_id);
image.innerHTML = '<img src='+imageSrc+' />'
var firstPicture = document.getElementById(firstMove);
if (imageSrc == prevImageSrc) {
firstMove=0;
} else {
// code will run after 1s delay
setTimeout(function () {
image.innerHTML = "";
firstPicture.innerHTML = "";
firstMove=0;
}, 1000); // delay = 1 second
}
} else {
var image = document.getElementById(clicked_id);
image.innerHTML = '<img src='+pictures[clicked_id-1]+' />'
firstMove = clicked_id
}
}

I can't get id of a image in javascript

I want to get the id of my img in javascript on a mousewheel but when I do a getElementById I it tells me that the length is null
this is the function where I put my img
function parse_data(data)
{
var json = data;
var obj = JSON.parse(json);
var buff = "";
for(var i in obj)
{
//document.write('<br>' + i + '<br>');
for (var j in obj[i])
{
if (obj[i][j] == true)
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
else
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
}
buff += "<br>";
}
document.getElementById('frisekk').innerHTML = buff;
}
And this is the function where I want to get back the id of an img on mousewheel
function test()
{
var obj = document.getElementById('img');
alert(obj.length); //obj.length is null...
if (event.wheelDelta >= 120)
unit -= 60;
else
unit += 60;
request(readData);
}
how could I get the id of my img ?
there is all the html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script>
var unit = 60;
var date = 'Mon Oct 20 2014 19:25:00 GMT (CET)';
function request(callback)
{
var xhr = getXMLHttpRequest();
var frise = 600;
var template = 'lab';
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
callback(xhr.responseText);
};
xhr.open("GET", "a.php?Frise=" + frise + "&Unit=" + unit + "&Template=" + template + "&Date=" + date, true);
xhr.send(null);
}
function readData(sData)
{
parse_data(sData);
}
function parse_data(data)
{
var json = data;
var obj = JSON.parse(json);
var buff = "";
for(var i in obj)
{
//document.write('<br>' + i + '<br>');
for (var j in obj[i])
{
//document.write(j + "=" + obj[i][j] + '<br>');
if (obj[i][j] == true)
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
else
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
}
buff += "<br>";
}
document.getElementById('frisekk').innerHTML = buff;
}
function test()
{
var obj = document.getElementById('img');
alert(obj.length);
if (event.wheelDelta >= 120)
unit -= 60;
else
unit += 60;
request(readData);
}
</script>
<script>
function getXMLHttpRequest()
{
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
xhr = new XMLHttpRequest();
}
}
else
{
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
</script>
<span id="frisekk"> <br/> </span>
</head>
<body>
<form>
<p>
<input type="button" onclick="request(readData);" value="Exécuter" />
</p>
</form>
</body>
</html>
document.getElementById does not get the id for you, it gets the element by id passed. Since you didn't post your HTML I can't really say whether your <img /> tag has the id of img, but I'm assuming not. What you are looking for is document.getElementsByTagName('img') to get tevery img element on the page and then use a loop to find which one you need (or add [0] if you know you only have one to select the first element).
So you have two options:
Add an ID to your element (best option)
<img src="path/to/image.jpg" id="my_image" />
var finalElement = document.getElementById("my_image");
Find all elements with the tagname 'img' and then search through them for the right on
<img src="path/to/image.jpg" />
var elements = document.getElementsByTagName("img");
var finalElement = false;
for(var i = elements.length -1; i >= 0; i--){
// match your element and return
if(/* criteria */){
finalElement = elements[i];
break;
}
}
Have only one image on your page and select that:
<img src="path/to/image.jpg" id="my_image" />
var finalElement = document.getElementsByTagName("img")[0];
Update
Your onmousewheel property could be supported, but then you need to do it slightly differently, because your link has the onmousewheel event.
<!-- add the 'this' keyword to your test() function to pass the <a> element -->
<img src="path/to/image.jpg" />
With this structure (one <img> nested in an <a>), you can pass the <a> to the function using the thiskeyword.
/* Add a variable to receive your <a> in your test() function. */
function test(link){
/* Use childNodes[0] to select the first child element of the a. */
var image = link.childNodes[0];
/* Will alert '1' if the <a> has a child, will alert '0' if the <a> is empty.*/
alert(image.length);
}
Now you can easily access the only child of the a element, the image, and do something with that.
I am not sure whether onmousehweel is supported on an element, so pelase consider an onclick or onmouseover to test this function. If you decide to test with onmouseover, use the console.log to log instead of alert, otherwise you'll drown in alerts.
Can't you parse the id in the function call?
Eg in:
onmousewheel=test(obj[i])
and in the function,
function test(id)??

Javascript image to div

So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<img src="images/Tulip_small.jpg" alt="Tulips">
<img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips">
<img src="images/Swan_small.jpg" alt="Swan on Lake">
<img src="images/Red_Tulip_small.jpg" alt="Red Tulips">
<img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees">
<img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video">
</div>
Change the class attribute to id or add the id attribute id="html5gallery"
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
EDIT:
Try this to append image
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!
If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: DEMO
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>

jQuery / JavaScript Scope: Getting Variables Into and Out Of Functions

I have a simple image rotator script that I'm trying to build but I am having trouble learning scope as it relates to getting variables into and out of JavaScript functions.
Here is my code:
<script type="text/javascript">
jQuery(document).ready(function($) {
function indexUp () {
if (slide_curr == slide_max - 1) {
slide_curr = slide_max;
slide_prev = slide_max - 1;
slide_next = slide_min;
} else if (slide_curr == slide_max) {
slide_curr = slide_min;
slide_prev = slide_max;
slide_next = slide_min + 1;
} else {
slide_curr = slide_next;
slide_prev = slide_curr - 1;
slide_next = slide_curr + 1;
}
}
function doTransition () {
// turn on the display of the next slide
$(slides[slide_next]).css('display','block');
// fade the current slide out (to zero opacity)
$(slides[slide_curr]).fadeOut(600, function() {});
}
function printState () {
var state_str = 'slide_curr='
+ slide_curr
+ '; slide_prev='
+ slide_prev
+ '; slide_next='
+ slide_next
+ '; slide_max='
+ slide_max
+ '; slide_min='
+ slide_min;
$('#bx_state').html(state_str);
}
function doIt () {
doTransition();
indexUp();
printState();
}
// variables
var slides = $('#bx_slider img');
var slide_min, slide_max, slide_curr, slide_prev, slide_next;
// initialize the settings
slide_min = 0;
slide_max = slides.length - 1;
slide_curr = 0;
slide_prev = slide_max;
slide_next = 1;
// start it all off when the page loads
$(slides[slide_curr]).css('display','block');
timeout = setTimeout(doIt, 3000);
});
</script>
<style type='text/css'>
#bx_slider img {
display:none; position:absolute;}
#bx_slider {
width:922px; height:530px; margin:100px auto;
position:relative;}
</style>
<div id="bx_slider">
<img src="slide1.jpg" />
<img src="slide2.jpg" />
<img src="slide3.jpg" />
<img src="slide4.jpg" />
<img src="slide5.jpg" />
</div><!-- #bx_slider -->
<div id='bx_state'></div>
I'm trying to get the slide_curr, slide_next, and slide_prev to change each time the script is run and then print those out to the page in the div tag in an effort to see what is going on; however, even that is not working for me.
Here is the script in action: http://www.exit44.com/slider/
Thanks for the help.
I'm guessing here, but perhaps the problem has nothing to do with variable scope. You mention that you want to create a "simple image rotator". Try changing
timeout = setTimeout(doIt, 3000);
to
timeout = setInterval(doIt, 3000);

javascript onclick, anonymous function

I am a beginning javascript programmer. I am trying to create something similar to Lightbox 2, but much simpler. The only reason why I want to do it from scratch on my own is so that I can learn. However, I've been stuck on the last critical part where it displays the image. I believe the problem lies where I try to use onclick with assignment to an anonymous function:elem[i].onclick = function (){liteBoxFocus(imgSource,imgTitle); return false;};
. If you run my code and try clicking on the google logo it'll bring up the yahoo logo and title instead of google's logo and title. However when you click on the yahoo logo it works fine so it seems that the anonymous function only holds for the last loop. Thanks in advance!!!
I have placed the entire CSS/JS/XHTML in one page for your convenience.
<html>
<head>
<title>Erik's Script</title>
<style type="text/css">
#liteBoxBg, #liteBox {
display: none;
}
#liteBoxBg {
background-color: #000000;
height: 100%;
width:100%;
margin:0px;
position: fixed;
left:0px;
top: 0px;
filter:alpha(opacity=80);
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
z-index: 40;
}
#liteBox {
background-color:#fff;
padding: 10px;
position:absolute;
top:10%;
border: 1px solid #ccc;
width:auto;
text-align:center;
z-index: 50;
}
</style>
<script type="text/javascript">
window.onload = start;
function start(){
var imgTitle = "No title";
var imgSource;
var elem = document.getElementsByTagName("a");
var i;
//Dynamically insert the DIV's to produce effect
var newDiv = document.createElement('div');
newDiv.setAttribute("id", "liteBox");
document.getElementsByTagName("body")[0].appendChild(newDiv);
newDiv = document.createElement('div');
newDiv.setAttribute("id", "liteBoxBg");
document.getElementsByTagName("body")[0].appendChild(newDiv);
//Check those anchors with rel=litebox
for(i = 0;i < elem.length;i++){
if(elem[i].rel == "litebox"){
imgSource = elem[i].href.toString();
imgTitle = elem[i].title;
elem[i].childNodes[0].style.border="0px solid #fff";
elem[i].onclick = function (){liteBoxFocus(imgSource,imgTitle); return false;};
}
}
//When foreground is clicked, close lite box
document.getElementById("liteBoxBg").onclick = liteBoxClose;
}
//Brings up the image with focus
function liteBoxFocus(source,title){
document.getElementById("liteBox").style.display = "block";
document.getElementById("liteBox").innerHTML = "<h1>" + title + "</h1>" +
"<img src='" + source + "'/><br />" +
"<a href='#' onclick='liteBoxClose();'><img src='images/litebox_close.gif' border='0' alt='close'/></a>";
document.getElementById("liteBoxBg").style.display = "block";
}
//closes lite box
function liteBoxClose(){
document.getElementById("liteBox").style.display = "none";
document.getElementById("liteBoxBg").style.display = "none";
return false;
}
</script>
</head>
<body>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="" />
<a href="
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg" rel="litebox" title="Yahooo Logo"><img src="
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg" alt="" /></a>
</body>
</html>
Your event handlers form a closure that remember a "live" pointer to the variables in the enclosing scope. So when they are actually executed, they have the last value imgSource and imgTitle had.
Instead, you can use this pattern to localize the variable values. This will create copies of source and title inside getClickHandler each time it is called. The returned function hence remembers the values in that iteration of the loop.
//Check those anchors with rel=litebox
for(i = 0;i < elem.length;i++){
if(elem[i].rel == "litebox"){
imgSource = elem[i].href.toString();
imgTitle = elem[i].title;
elem[i].childNodes[0].style.border="0px solid #fff";
elem[i].onclick = getClickHandler(imgSource, imgTitle);
}
}
//Brings up the image with focus
function getClickHandler(source,title){
return function() {
document.getElementById("liteBox").style.display = "block";
document.getElementById("liteBox").innerHTML = "<h1>" + title + "</h1>" +
"<img src='" + source + "'/><br />" +
"<a href='#' onclick='liteBoxClose();'><img src='images/litebox_close.gif' border='0' alt='close'/></a>";
document.getElementById("liteBoxBg").style.display = "block";
}
}

Categories