variable inside getelementbyid in javascript not working - javascript

I want to reuse an image swap function on multiple divs, but the function is not acknowledging the adbox variable on the var rotator = getelementbyid(adbox).
window.onload = animatez(animate);
the animatez function should pass "animate" which is the div id to getelementbyid inside the function.
function animatez(adbox) {
var adbox;
var rotator = document.getElementById(adbox);
var images = rotator.getElementsByTagName("img");
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none"; }
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;}
}, 1000);
};
window.onload = animatez(animate);
<style>
#animate { width:200px; height:200px; background-color:transparent;
margin:auto; position:absolute;
}
img {width:200px; height:200px; display:none;}
</style>
<body>
<div id="animate">
<img src="surveyfunny.png">
<img src="myanswertoasurveyquestion.png">
<img src="funny-wheredoyoulive.png">
<img src="funnysurveyquestion2.png">
<img src="funnysurveyquestion.png">
</div>

You need give the function a string parameter. Without quote the animate is undefined, javascript throw the error.
see https://jsfiddle.net/pconline2046/u5cbwpuL/3/#
window.onload = function(){
animatez('animate');
};

window.onload needs to be set equal to a function, not the result of calling your animatez function. You could do something like this.
window.onload = function(){
animatez('animate');
};
Also notice that you need to pass a string to your animatez function so I have quoted animate.
Edit: Like some other answers have stated you also should remove the
var adbox;
line in your function.

Why do you have adbox var defined twice? Once at function animatez(adbox) { and again at var adbox...?

Related

Error in javascript when double clicking an img element to trigger an click event

<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title>imagegame</title>
<style>
body { margin: 20px; }
img { margin: 20px; }
</style>
</head>
<body>
<img id="pic1" src="img/charpter9/zeroblur.jpg">
<img id="pic2" src="img/charpter9/oneblur.jpg">
<img id="pic3" src="img/charpter9/twoblur.jpg">
<img id="pic4" src="img/charpter9/threeblur.jpg">
<img id="pic5" src="img/charpter9/fourblur.jpg">
<img id="pic6" src="img/charpter9/fiveblur.jpg">
<script>
function init() {
var imgs = document.getElementsByTagName("img");
for(var i = 0; i < imgs.length; i++){
imgs[i].onclick = onClick;
}
}
function onClick(e){
var img = e.target;
var imgsrc = img.src;
var imgid = img.id;
var imgsrc0 = imgsrc;
imgsrc = imgsrc.replace("blur","");
img.src = imgsrc;
setTimeout(refresh, 5000, imgsrc0, imgid);
}
function refresh(imgsrc,id){
var img = document.getElementById(id);
img.setAttribute("src",imgsrc);
}
window.onload = init;
</script>
</body>
</html>
above is the code, my main consideration is whether there is a plan to solve mouse double-click when clicking on one element whose trigger is onclick.
the error I found is when I double-click the image showed on the page, the pic can't be reblurrd automatically. the case is head-first javascript book chapter 9 on about page 142.
thank for your time.
enter image description here
The main issue is, that the second time the src has no blur anymore already and the time the second timeout is finished it gets set to that src instead of the one with the blur.
You could keep the original source in a data-attribute and set the src back on that attribute. Furthermore you can cancel the setTimeout() on doubleclicks.
function onClick(e){
var img = e.target;
var imgsrc = img.src;
var imgid = img.id;
var imgsrc0 = imgsrc;
//REM: Keep the original src
if(!img.getAttribute('data-img-src')){
img.setAttribute('data-img-src', imgsrc)
};
imgsrc = imgsrc.replace("blur","");
img.src = imgsrc;
//REM: Clear and reassign the timeout
clearTimeout(img.timeout); //REM: Dirty way, but fast to show
img.timeout = setTimeout(refresh, 5000, imgsrc0, imgid)
}
function refresh(imgsrc,id){
var img = document.getElementById(id);
//REM: Set the original src
img.setAttribute("src",img.getAttribute('data-img-src'));
img.removeAttribute('data-img-src')
}
Yet I think it would be much easier to keep all the images in an object and create the img on the fly. Also it makes your code unbound from a fixed naming scheme in your image sources. Like this for example:
var _Images = [
{Blurred: 'https://image.flaticon.com/icons/svg/172/172838.svg', Active: 'https://image.flaticon.com/icons/svg/196/196138.svg'},
{Blurred: 'https://image.flaticon.com/icons/svg/196/196138.svg', Active: 'https://image.flaticon.com/icons/svg/172/172838.svg'},
{Blurred: 'https://image.flaticon.com/icons/svg/172/172838.svg', Active: 'https://image.flaticon.com/icons/svg/196/196138.svg'}
];
window.onload = function(){
for(var i=0, j=_Images.length; i<j; i++){
var tImage = document.body.appendChild(document.createElement('img'));
tImage.src = _Images[i].Blurred;
tImage.setAttribute('width', '20px');
tImage.onclick = function(image){
this.src = image.Active;
window.clearTimeout(image.Timeout);
image.Timeout = window.setTimeout(function(){
this.src = image.Blurred
}.bind(this, image), 5000)
}.bind(tImage, _Images[i])
}
};

JavaScript Slideshow using onload and an image swapping function

My slideshow flips through images but one of them flips through the wrong image. Can someone please look through my code and find what I can't seem to find!Here is the html:
<div id="serv_tims">
<div id="serv_d"><img name='slide' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/1651756_orig.png'/></div>
<div id="serv_t"><img name='slide2' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6848746_orig.png'/></div>
<div id="serv_m"><img name='slide3' src='http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png'/></div>
</div>
Here is the css:
#serv_tims{
border:solid 4px #0276FD;
height:300px;
width:300px;
position:static;
float:right;
clear:right;
margin:0 0.5% 0 0;
}
#serv_d,#serv_t,#serv_m{
height:100px;
width:300px;
}
Here is my javascript:
var i = 0;
var path = new Array();
path[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/1651756_orig.png";
path[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6795103_orig.png";
path[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/8269055_orig.png";
function swapImage(){
document.slide.src = path[i];
if(i < path.length - 1){ i++;} else{i = 0;}
setTimeout("swapImage()",2000);
}
var j = 0;
var path2 = new Array();
path2[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/6848746_orig.png";
path2[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/5983713_orig.png";
path2[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/5808905_orig.png";
function swapImage2()
{
document.slide2.src = path[j];
if(j < path2.length - 1){ j++;} else{j = 0;}
setTimeout("swapImage2()",2000);
}
var k = 0;
var path3 = new Array();
path3[0]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
path3[1]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
path3[2]="http://jjoli.weebly.com/uploads/1/8/6/0/18608386/3044861_orig.png";
function swapImage3()
{
document.slide3.src = path3[k];
if(k < path3.length - 1){ k++;} else {k = 0;}
setTimeout("swapImage3()",2000);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(swapImage);
addLoadEvent(swapImage2);
addLoadEvent(swapImage3);
Allright I can propose you very simple solution to create your own slideshow
firstly assume that we want to have 5 images in our slide Show .
<div id="main_frame">
<div id="slide_frame">
<div class="imdiv"><img src="1.jpg" class="imgs" /></div>
<div class="imdiv"><img src="2.jpg" class="imgs" /></div>
<div class="imdiv"><img src="3.jpg" class="imgs" /></div>
<div class="imdiv"><img src="4.jpg" class="imgs" /></div>
<div class="imdiv"><img src="5.jpg" class="imgs" /></div>
</div>
</div>
the most important thing is the frame must be overflow:hidden and for instance your the width
your each frame is 500px so the width of the mainframe must be 500px and the witdh of slide frame
must be 500*5=2500px allright
<style>
#main_frame {border:1pxsolid;black;width:500px;height:300px;overflow:hidden;position:relative;}
#slide_frame {border:0px solid transparent;width:2500px;height:300px;position:relative;}
.imgs {width:500px;border:0px;height:300px;position:relative;}
</style>
then you need to have the library of jquery
as:
you will add this library into head tags
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
then write this javascript code
<script type="text/javascript">
$(document).ready(function(){
var slide=500;
var counter=0;
setInterval(function(){
var s=slide*counter;
$("#slide_frame").animate({left:s},600);
counter+=1;
if(counter==5)
counter=0;
},500);
});
</script>
add this javascript code declared upward into head tag .you do not need to call it will start
automatically
Good Luck
I run your code in a fiddle and this is not an image slide show, those are just text. You shouldnt use those kinda concept with images. It'll only make things messy. Here an example for what youre trying to achieve.
<div id="serv_tims">
<div>SUNDAY<br>MORNING</div>
<div>10:00 AM</div>
<div>GOD<br>LOVES YA</div>
</div>
js:
var i = 1;
var text = [
["SUNDAY<br>MORNING","10:00 AM","GOD<br>LOVES YA"],
["SUNDAY<br>EVENING","05:00 PM","GOD<br>LOVES YA"],
["SUNDAY<br>NIGHT","11:00 PM","GOD<br>LOVES YA"]
];
var st = document.getElementById("serv_tims");
setInterval(function(){
for(var j = 0; j < 3; j++){
st.children[j].innerHTML = text[i][j];
}
i = (i < (text.length - 1)) ? (i + 1) : 0;
},3000);
As you can see, you can just edit text array whatever the way you need.
FIDDLE
I see my problem!
document.slide2.src = path[j];
should be
document.slide2.src = path2[j];
Sorry!
One more thing the code I wrote for you is static.If you want to have new images to your
slide shows
For instance the I wrote was only for 5 images.However you can add more.But in order to do
this, you need expand the width of slide_frame when you add a new image every time.And append
the image into slide_frame div.If you want further info I can send you a code snippet that I
had written before
Good Luck

Dynamically pass random javascript array value to html img src

I'd like to dynamically pass an array value (in this case, String "../name1.jpg" or "../name2.jpg") to the img src <img src="here">. Each time you hover over "Class of 2013", a random image will fade in, then fade out.
Is that possible to pass in a value by calling it as such? <img src="getImages(); ?
How would you do it?
var ImgArray = new Array();
ImgArray[0] = "../name1.jpg";
ImgArray[1] = "../name2.jpg";
$(document).ready(function() {
show();
});
function show(){
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
function getImages() {
int i = Math.random() * (max - min) + min;
return ImgArray[i];
}
HTML:
<div class="box">
Class of 2013:
<div class="overlay"> <!-- Put images to display here...-->
<img src="getImages();" alt="image to be displayed" />
</div>
</div>​
Thank you
EDIT: Current Code:
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
var ITLP = new Array();
ITLP[0] = "/corp/itlp/ITLP%20Bios/DanTurcotte.jpg";
ITLP[1] = "/corp/itlp/ITLP%20Bios/gomezwilmann.jpg";
$(document).ready(function() {
showimg();
});
function showimg()
{
$(".box > .overlay > img").attr("src",getImages());
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
function getImages() {
int i = Math.abs(Math.random());
return ITLP[0];
}
</script>
</head>
<body>
<div class="box">
Class of 2013:
<div class="overlay"> <!-- Put images to display here...-->
<img src="" border="none"/>
</div>
</div>​
</body>
</html>
I prefer the classic way:
$(".box > .overlay > img").attr("src",getImages());
Extension:
function show()
{
$(".box > .overlay > img").attr("src",getImages());
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); } ,
function(){ $(this).find(".overlay").fadeOut(); }
);
}
I think your requested way doesn't work, because the browser expect a string for the source attribute.
P.S.: Take an eye on your random function. My Firefox did complain something "(missing ';' before statement")
You may try this
var ImgArray = new Array();
// add images
$(document).ready(show);
// Show function
function show(){
$('img').attr('src', ImgArray[0]).parent().hide();
var max = ImgArray.length;
$(".box").hover(
function(){ $(this).find(".overlay").fadeIn(); },
function(){
var img = $(this).find(".overlay").find('img');
var i = Math.floor(Math.random()*max);
$(this).find(".overlay").fadeOut(function(){
img.attr('src', ImgArray[i]);
});
}
);
}
DEMO.
You want to change the source of the image in your first hover function (the one with fadeIn).
Since you're already using jQuery, just do this:
function(){ $(this img).attr("src", getImages()); $(this).find(".overlay").fadeIn(); } ,
and set your img's src initially to "". Of course, you could simplify your jQuery if you added an id to the img tag.
EDIT
I set up a fiddle with a working example here.
This is the script code:
var ITLP = [];
ITLP[0] = "http://lorempixel.com/400/200/nature";
ITLP[1] = "http://lorempixel.com/400/200/city";
function getImages() {
var i = Math.floor(Math.random() * (ITLP.length + 1)); // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FMath%2Frandom
console.log(ITLP[0]);
return ITLP[0];
}
function showimg() {
$(".box").hover(
function () {
console.log("Hover start");
$(".box > .overlay > img").attr("src", getImages());
$(this).find(".overlay").fadeIn();
},
function () {
console.log("Hover end");
$(this).find(".overlay").fadeOut();
});
}
showimg();
Major things I did:
Ordered the functions to be declared before they're used.
Got rid of the int i declaration that was killing getImages()
To get it this far, I used the console log a lot, and also jsfiddle's JSHint is a big help.

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Toggling between two images by clicking

Due to this link
I changed it to this one:
<html>
<head>
<script>
var toggleimage=new Array("p1.gif","p.gif")
//do not edit the variables below
var image_1=new Image()
var image_2=new Image()
image_1.src=toggleimage[0]
image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
onload=testloading
</script>
<title>
</title>
<meta content="">
<style></style>
</head>
<body>
<img name="togglepicture" src="p1.gif" border="0">
</body>
</html>
when I click on the image p it will show me p1 and vice versa
Now I have problem image has a name:
<img name="togglepicture" src="p1.gif" border="0">
and it will get the name here:
document.togglepicture.src=toggleimage[i_image]
I want to have many images so I thaught I need to change the togglepicture to a variable
for example:
function toggle(a) {
if (isloaded) {
document.a.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
and for input forexample it will be toggle('nameofimage') and in the href it will be something like
<a href="javascript:toggle('pic1')">
I wasn't successful.How can I use this function when I have more than a picture to click?
I made a modular toogle, visible here: http://jsfiddle.net/Regisc/N7bgz/2/
Usage sample:
<img id="image1" src="http://dummyimage.com/50/f00/fff&text=a"
onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b",
"http://dummyimage.com/50/ab0/fff&text=c"]);' />
you can't use
document.a.src=toggleimage[i_image];
instead use
document.getElementById(a).src=toggleimage[i_image];
And you also need to add an id to your img element.
Something like the following should work for any number of images provided toggleimage is a contiguous array.
var toggleimage = ["p1.gif","p.gif"];
var toggle = (function() {
var count = 0;
var len = toggleimage.length;
var el = document.getElementsByName('togglepicture')[0]
return function() {
if (isloaded) {
el.src = toggleimage[count++ % len];
}
};
}());
I'm not entirely sure I got your question. Are you asking:
How to edit the function to allow toggling between more than just two images, or
How to edit the function to handle more than one set of toggle images?
Toggling between more than just two images
var toggleimage=new Array("p1.gif","p.gif","p2.gif","p3.gif","p4.gif")
var totalImages=4;
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>totalImages) {i_image=0}
}
How to edit the function to handle more than one set of toggle images?
call the JS function like this
<a href="javascript:toggle(this)">
And, in your JS function,
var id = div.id;
Use this in an if-else to determine which control called the function and accordingly which array of images to use.
function toggle(div)
{
var id = div.id;
if (isloaded)
{
if (id == 'myFirstToggleImageControl')
{
document.togglepicture.src=toggleimage[i_image];
}
else if (id == 'mySecondToggleImageControl')
{
document.togglepicture.src=toggleimageSource2[i_image];
}
}
i_image++
if (i_image>1) {i_image=0}
}
Note: You will want to use an independent counter for the second control. So, possibly i_image1 and i_image2
<html>
<head>
<script>
// images list (properties name must by equal to id of IMAGE html element)
var imageList={
image1: {
currentIndex:0,
images:["p1.gif","p.gif"]
}
};
// preloading images using closure (additionaly replace image URL's with image objects)
(function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
for(var i=0;i<imageList[p].images.length;i++) {
var img=new Image(),src=imageList[p].images[i];
(imageList[p].images[i]=img).src=src;
}
}
})();
function toogleImage() {
var info=imageList[this.id];
info.currentIndex++;
if(info.currentIndex===info.images.length)info.currentIndex=0;
this.src=info.images[info.currentIndex].src;
}
// setting start images
window.onload=function() {
for(var p in imageList)if(imageList.hasOwnProperty(p)) {
//try{
document.getElementById(p).src=imageList[p].images[0].src;
//}
//catch(ex){}
}
}
</script>
</head>
<body>
<img id="image1" onclick="toogleImage.call(this);"/>
</body>
</html>
http://jsfiddle.net/X4Q2m/

Categories

Resources