JavaScript: Function to change images with onClick not working. - javascript

I have 6 pictures of the lovely Serena Williams, I've been researching how to change the images every time I click on them. However the code is not working, please help me identify whether I've made a logic or syntax error:
<html>
<head>
<title>SerenaWilliams</title>
</head>
<body>
<img src="http://1.bp.blogspot.com/-hGUyOlpoeB0/UROyeHgMXcI/AAAAAAAAAZ4/L32zLAQvQj0/s1600/Hot-Serena-Williams+_sexy+16.jpg" id="serenaGallery" onclick="changeImage" />
</body>
<script type="text/javascript">
function changeImage() {
var currentImage = document.getElementById("serenaGallery").src;
var image1 = "http://1.bp.blogspot.com/-hGUyOlpoeB0/UROyeHgMXcI/AAAAAAAAAZ4/L32zLAQvQj0/s1600/Hot-Serena-Williams+_sexy+16.jpg";
var image2 = "http://usatthebiglead.files.wordpress.com/2011/04/serena-williams-is-big-boned.jpg";
var image3 = "http://www.strangecosmos.com/images/content/109963.jpg";
var image4 = "http://1.bp.blogspot.com/-HiJxcIjMmFg/UWo9JtbfCEI/AAAAAAAAF1g/aUU42F3V9Ic/s1600/Serena+Williams+Hot+2013+04.jpg";
var image5 = "http://mystarclub.com/wp-content/uploads/2012/11/Serena-Williams-is-a-Bikini-Babe.jpg";
var image6 = "http://1.bp.blogspot.com/-vCsx4sswzeM/UA5GtbEwJ1I/AAAAAAAAACE/tMiP_p-0rB0/s1600/serena+williams+tennis+ball+in+butt.jpg";
if (currentImage==image1){ currentImage=image2; }
if (currentImage==image2){ currentImage=image3; }
if (currentImage==image3){ currentImage=image4; }
if (currentImage==image4){ currentImage=image5; }
if (currentImage==image5){ currentImage=image6; }
else { currentImage=image1; }
}
</script>
</html>

First of all, you need to modify the onclick attribute so it will actually execute the function:
onclick="changeImage()"
The command
var currentImage = document.getElementById("serenaGallery").src;
just stores the source attribute of the image in a variable; it doesn't reference it.
Also, you have to change all if statements to else if or the function will change image1 to image2, then to image3, etc.
This would work:
var currentImage = document.getElementById("serenaGallery");
...
if (currentImage.src == image1){ currentImage.src=image2;}
else if (currentImage.src == image2){ currentImage.src=image3;}
...
Lastly, using an array for the image sources would allow you to condense the if statements into a single for loop. Not really needed for six images, but better if you want to add more.

Related

Changing picture serveral times by click in HTML with javascript

I need a programm in HTML with javascript which has two pictures that by click changes from picture A to B and from picture B to A and so on. I think I need a loop...
Please Try Following Code
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
You Can Have example here https://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb
you can find a good example of what you want to do in here:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb
you just need to tweak it a bit so it will change the images correctly.
I would recommend building a function with variables to store the images name.
<script>
function ChangeImage(){
var picElement1 = document.getElementById('HTMLImgElement1');
var picElement2 = document.getElementById('HTMLImgElement2');
var temp = picElement1.src;
picElement1.src = picElement2.src;
picElement2.src = temp;
}
</script>
In the html just set up 2 images with ID HTMLImgElement1 and HTMLImgElement2.
and a button with an onclick attr that will forward to this function.

Cycling images with javascript

Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.
<!DOCTYPE html>
<html>
<body>
<script>
function changeImg() {
if (document.getElementById("cycle").src == "fox.jpg") {
document.getElementById("cycle").src = "hawk.jpg";
} else {
document.getElementById("cycle").src = "ant.jpg";
}
}
</script>
<button onclick = "changeImg()">change image</button>
<img id ="cycle" src ="fox.jpg"/>
</body>
</html>
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.
With this solution, you can add as many images to the images array as you like, without touching the code/logic;
<!DOCTYPE html>
<html>
<body>
<button onclick="changeImg()">change image</button>
<img id="cycle" />
<script>
var imageElement = document.getElementById("cycle");
var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
var counter = 0;
imageElement.src = images[counter] // set the initial image
function changeImg() {
counter = (counter + 1) % images.length;
imageElement.src = images[counter];
}
</script>
</body>
</html>
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar from fox.jpg.
You need try another solution.Try use
cycle.getAttribute('src')
Example code:
function changeImg() {
let cycle = document.getElementById("cycle");
console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {cycle.src = "ant.jpg";
}
}
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.
var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {
cycle.src = "ant.jpg";
}

How to make an image change into others on click?

I'm trying to make a sort of a minimal clickable "slideshow". So far I have only managed to make the image change into another. but I want to add other images to it. I tried to add other ifs and elses on the javascript but it doesn't work. (I'm a noob...) How can I do it? I juts want to click and the images change. This is my code so far:
<div> <img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage()"/> </div>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "1.jpg")
{
document.getElementById("imgClickAndChange").src = "2.jpg";
document.getElementById("imgClickAndChange").src = "3.jpg";
}
}
</script>
thank you!
In your condition you need a double equals == - you can also pass this in to avoid getElementById multiple times. If you want to make a cycler - you can put your sources into an array and cycle thru that:
<img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage(this)"/>
var images = ["1.jpg", "2.jpg", "3.jpg"];
function changeImage(img) {
var currentIndex = images.indexOf(img.src);
var zeroBasedLength = images.length - 1;
if (currentIndex == zeroBasedLength)
img.src = images[0];
else
img.src = images[++currentIndex];
}
If you want to cycle through those images, I'd make an array and swap the position of the elements in it like:
var imgs = ["2.jpg", "3.jpg", "1.jpg"];
function changeImage() {
document.getElementById("imgClickAndChange").src = imgs[0];
imgs.push(imgs.shift())
}
jsFiddle example

updating javascript function without realoding

Im trying to build an embedded web server with Nano WiReach SMT
So far i have wrote this code
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
function swapImage() {
var val1 = "~Value1~"
val1=Number(val1);
intImage = val1;
switch (intImage) {
case 0:
IMG1.src = "off.jpg";
return(false);
case 1:
IMG1.src = "on.jpg";
return(false);
}
setTimeout("swapImage()",500)
}
swapImage()
</SCRIPT>
</HEAD>
<BODY>
<body onload="swapImage()">
<IMG id="IMG1" name="IMG1" src="on.jpg">
</BODY>
</HTML>
Through some AT+i commands to the Nano WiReach SMT i can change the ~Value1~ content, and by sending "0" and "1" i cant change the images. Now in order to change the image i have to always reload the page through the browser..
I wonder if there is anyway to do that automatic in some specified time period or even better when the Value1 changes without reloading the hole page..
Maybe put it on a div and reload just the div content but i dont know how..
One last thing..searching the web i found something similar with jquery..i cant use jquery cause the libs are very big for my uC..
Thank you
Are you missing the following?
var IMG1 = window.document.getElementById("IMG1");
Also does your function need a name?
!function() {
var val1 = "~Value1~"
val1=Number(val1);
var intImage = val1;
var IMG1 = window.document.getElementById('IMG1');
switch (intImage) {
case 0:
IMG1.src = "off.jpg";
return(false);
case 1:
IMG1.src = "on.jpg";
return(false);
}
setTimeout(arguments.callee, 500);
}();
It's better to send a function to setTimeout instead of a string, otherwise
the string eval is performed on the string in the global context - not always what you want.
I haven't tested this code, and not sure about your platform, but you'll probably want to preload the images and in addition reference the element in the body by id to change it's source.
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
var IMG1 = new Image();
IMG1.src = "on.jpg";
var IMG2 = new Image();
IMG2.src = "off.jpg";
function swapImage() {
var oIMG = document.getElementById("IMG1");
var val1 = "~Value1~"
val1=Number(val1);
intImage = val1;
switch (intImage) {
case 0:
oIMG.src = IMG2.src;
return(false);
case 1:
oIMG.src = IMG1.src;
return(false);
}
setTimeout("swapImage()",500)
}
</SCRIPT>
</HEAD>
<BODY>
<body onload="swapImage()">
<IMG id="IMG1" name="IMG1" src="on.jpg">
</BODY>
</HTML>
Before we examine modules and inserting things with ~, etc. Let's make sure we can do a base script that works just fine. The following you can load in a normal browser, and it swaps the image back and forth every 500ms. setInterval causes the function to be called every 500ms, setTimeout will just call it once. Use which ever you want.
See if you can get this base script working, as it should, before trying other stuff. Ask any questions if you have any about it.
<!DOCTYPE html>
<html>
<head>
<title>Image Test</title>
<script language="javascript" type="text/javascript">
var IMG1 = new Image(); // create new image
var IMG2 = new Image(); // crete another new image
function init() {
IMG1.src = "on.jpg"; // preload on.jpg
IMG2.src = "off.jpg"; // preload off.jpg
var oIMG = document.getElementById("oIMG"); // grab a reference to img in doc with id of oIMG
oIMG.src = IMG1.src; // initially set the source of oIMG to IMG1's source
oIMG.toggled = 1; // initially give oIMG a toggled state of 1 (meaning on)
setInterval("swapImage()",500); //start time out for swapping image
}
function swapImage() {
var oIMG = document.getElementById("oIMG"); // grab a reference to img in doc with id of oIMG
switch (oIMG.toggled) { //switch based on the oIMG toggle state
case 0: //if off, turn it on
oIMG.src = IMG1.src;
oIMG.toggled = 1;
break;
case 1: //if on, turn it off
oIMG.src = IMG2.src;
oIMG.toggled = 0;
break;
}
}
window.onload = init;
</script>
</head>
<body>
<img id="oIMG" src="" />
</body>
</html>

JavaScript to change images

I have set of images named as img1, img2, img3, img4,......., imgx. So, I want to code a JavaScript to display an image img1 at document.onload() and on first click image to be changed to img2 next on second click the image to be changed at img3 and then same to the next image on every NEXT button click. In this manner I need even PREVIOUS button to go back to the previously viewed images.
How to implement this?
var currentImage = 1;
window.onload = function() {
showImage();
};
document.getElementById("next").onclick = function() {
currentImage++;
showImage();
}
function showImage() {
document.getElementById("image").src = "img" + currentImage + ".jpg";
}
These are the basics and should help you get started. If you need help implementing the rest, ask us what you want to do specificially and what you tried. Hint, you'll need to handle the case where there is no "next" image to show. Do you want it to come back to the beggining or just not work?
<script type="text/javascript">
var images = new Array("img/image1.jpg", "img/image2.jpg", "img/image3.jpg");
var cur_image = 0;
function goNextImage() {
var img = document.getElementById('image');
cur_image++;
if (cur_image == images.length) {
cur_image = 0;
}
img.src = images[cur_image];
}
</script>
<img src="img/image1.jpg" id="image" onclick="goNextImage()" />

Categories