Toggling between two images by clicking - javascript

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/

Related

The array won't work with the output of my pictures

I tried to show pictures with an array so I can change it per delay, kinda like a slideshow. The problem is, that only the first picture will load. when the counter of the array changes, the picture won't load.
The paths of the images are all correct
<!DOCTYPE html>`enter code here`
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<script>
var bilder = [];
var zeit = 3000;
var p = 0;
bilder[0] = "../Bilder/Bild1.jpg";
bilder[1] = "../Bilder/Bild2.jpg";
bilder[2] = "../Bilder/Bild3.jpg";
bilder[3] = "../Bilder/Bild4.jpg";
function BildAutoWeiter()
{
document.bild.src = bilder[p];
for( var i=0; i<= bilder.length; i++)
{
if(i <= bilder.length)
{
p++;
}
else
{
i = 0;
}
}
setTimeout("BildAutoWeiter()", zeit);
}
</script>
</head>
<body onload="BildAutoWeiter()">
<div>
<img name ="bild" width="100%" height="50%">
</div>
</body>
</html>
You need to use getElementsByName() to choose elements by their name=''. That returns an array of elements that use that name, so to choose a specific one, use an index [index] starting from 0. Do this instead:
document.getElementsByName('bild')[0].src = bilder[p];
That selects the first element that uses name='bild'
Also, the for statement is a bit useless. You could instead do:
function BildAutoWeiter()
{
document.bild.src = bilder[p];
p++;
setTimeout(BildAutoWeiter, zeit);
}
You don't need to put the function name in quotations and you can't have the parentheses while calling the function in setTimeout.

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

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.

Toggle image src attribute using Javascript

I am trying to change the HTML image src using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img tag and have written a Javascript function to change the image src when clicked.
Problem is that I want to change it back again when user clicks on the image.
For example when the page is loaded the Plus.gif shows and when user clicks on it the image it changes to Minus.gif.
I want it so, when the image is Minus.gif and user clicks on it this should be changed to Plus.gif.
Here is my Javascript function:
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src; //= 'Images/Minus.gif';
if (img) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else if (!img) {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
}
</script>
Image tag:
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
See the changes I made to make it working
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src;
if (img.indexOf('Plus.gif')!=-1) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
}
else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
}
}
</script>
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
Hope that resolves your question.
One way would be to add a toggle variable in your function:
var toggle = false;
function chngimg() {
if (toggle === true) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
toggle = !toggle;
}
Note that it's a better practice to use a sprite for this kind of thing. If you're using two images, the user experience is going to be clunky, because the first time they click the image, there will be a slight delay while the second image loads.
Ideally you would have the two images as a sprite sheet, and be using JQuery. Then you could just do it like this.
HTML
<img id="imgplus" src="Images/Sprite.gif" onclick="chngimg()" />
CSS
#imgplus .clicked { background-position: 0 -30px; }
Javascript
function chngimg() {
$("#imgplus").toggleClass("clicked");
}
I have successfully used this general solution in pure JS for the problem of toggling an img url:
function toggleImg() {
let initialImg = document.getElementById("img-toggle").src;
let srcTest = initialImg.includes('initial/img/url');
let newImg = {
'true':'second/img/url',
'false':'initial/img/url'}[srcTest];
return newImg;
}
Then call toggleImg() inside whatever event handler you use....
someButton.addEventListener("click", function() {
document.getElementById("img-toggle").src = toggleImg();
}

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>

Categories

Resources