Changing Image onclick with JavaScript - javascript

Hey i want to change a image when the img is clicked with javascript it works once if i click the picture it changes the scr but doesnt change it back
function ImgClick() {
var img = document.getElementById("b1")
if (img.src = "img/RoteAmpel.jpg") {
img.src = "img/GrueneAmpel.jpg";
} else {
img.src = "img/RoteAmpel.jpg";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Mouse Events</title>
<meta charset="UTF-8">
</head>
<body>
<h3>Mouse Events</h3>
<img src="img/RoteAmpel.jpg" alt="Bildwechsel" title="Bildwechsel" id="b1" onclick="ImgClick()" />
</body>
</html>

There are two problems with your code:
1. Assignment vs Comparison
You're assigning the src instead of making a comparison:
if (img.src="img/RoteAmpel.jpg") { }
should be
if (img.src === "img/RoteAmpel.jpg") { }
2. img.src might not be what you expect
When accessing img.src you'll get the full qualified URL including protocol, domain etc.
To compare the actually attribute's value use this:
img.getAttribute('src')
You can test it yourself:
function test() {
var img = document.getElementById("b1")
console.log(img.src);
console.log(img.getAttribute('src'));
}
test();
<img id="b1" src="img/RoteAmpel.jpg">

Related

How to make eventlistener add image to my page?

I have a button. When I click the button, I want an image of a cat to be created. I have created a function to do this. I have added an event listener to the button that triggers the function when the button is clicked. But no such image is created. Here's the code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="1">hello</button>
<script>
function create(){
var image= document.createElement("img")
image.src="https://encrypted-tbn0.gstatic.com/images?
q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU"
document.body.appendChild(image)
}
var element=document.getElementById("1")
element.addEventListener("click", create)
</script>
</body>
</html>
That because the url got corrupted and white space got introduced between images? and next line. Concat them using + or copy the url , try in the browser and then copy the same url from browser and put it between quotes
function create() {
var image = document.createElement("img")
image.src="https://encrypted-tbn0.gstatic.com/images?"+
"q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU";
document.body.appendChild(image)
}
var element = document.getElementById("1")
element.addEventListener("click", create)
<button id="1">hello</button>
Add semicolons and remove the linebreak in the url:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="1">hello</button>
<script>
function create(){
var image= document.createElement("img");
image.src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU";
document.body.appendChild(image);
}
var element=document.getElementById("1");
element.addEventListener("click", create);
</script>
</body>
</html>

checking code of Javascript "on mousedown"

<script>
function lighton() {
document.getElementById('myimage').src = "images\download.png";
}
function lightoff() {
document.getElementById('myimage').src = "images\link.png";
}
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function lighton() {
document.getElementById('myimage').src = "images\download.png";
}
function lightoff() {
document.getElementById('myimage').src = "images\link.png";
}
</script>
</head>
<body>
<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()" src="images\link.png" width="100" height="180" />
<p>Click mouse and hold down!</p>
</body>
</html>
see why this is not working when i click the mouse button first image disappears and second image does not open
I attached the event handers this way, and it started working. Remember to do this after "onload".
var el = document.getElementById("myimage");
el.addEventListener("mousedown",lightoff);
el.addEventListener("mouseup",lighton);
The error I was seeing with your code was that it could not find the functions.

JavaScript replace img src with External src

I'm having a strange problem that I can't quite figure out.
I have a normal image on a web page
<img src="images/logo.png"/> <!-- getting image from root directory -->
and I have some javascript code to replace the image source
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; image++)
image[num].src = image[num].src.replace("images/pic01.png", "images/other/pic02.png")
}
This code works fine which is great although it seems to fall down as soon as the src I want it replaced to is outside of my root directory such as "http://www.servername.com/pic03.png" // (this is an imaginary URL don't try to click it).
is there a reason this happens? is there a way around this?
The problem is that you are only replacing the last part of your original src. The src of the img tag first looks like this:
"http://yourserver.com/images/pic01.png"
...and after replacing "images/pic01.png" with you external URL, it looks like this:
"http://yourserver.com/http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png"
To avoid this problem you can try this:
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; num++) {
if (stringEndsWith(image[num].src, "images/pic01.png")) {
image[num].src = "http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png";
}
}
}
function stringEndsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1
}
There's also an error in your for loop, where you are incrementing image instead of num
Step-by-step explanation
imageUpdate()
Loop through each img tag and look at the src attribute
If src ends with "images/pic01.png" replace all of src with the new url
stringEndsWith()
Find index of given suffix (start looking for the suffix at the last possible position
the suffix can be located at)
If this index is found (is different from -1) return true, else return false
What target url are you assigning to it? Make sure that it is pointing to an absolute address (keep the http:// part at the beginning).
If the file is in the same server, you can still use relative file paths, and go up a parent folder by using two dots. For instance: ../someotherfolder/pic03.jpg
<script>
function imageUpdate() {
document.getElementById('imageT').src = 'test.jpg';
}
</script>
<img id='imageT' src="images/logo.png"/> <!-- getting image from root directory -->
JS Fiddle-Demo
There is an error in the link you are trying to use. The actual link should be:
http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png
Here is come code to demonstrate:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
function changeImage() {
document.getElementById('changeThis').src = 'http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png'
}
</script>
</head>
<body>
<img id="changeThis" src="http://www.wartburgseminary.edu/uploadedImages/Resources/small-twitter-icon.jpg">
<input type="button" value="Change" onClick="changeImage()">
</body>
</html>

Multiple Onclick images

SO I am trying to create a screen that will display about 50 toggle buttons to display in a building on a monitor.
I want to create a bunch of images to use as the toggle so they are easy to see. This is the effect I want.
http://www.w3schools.com/dhtml/tryit.asp?filename=trydhtml_intro
except picture I want several light bulbs to turn on and off as I want.
Right now this is the code I have.
I am able to click the images to change as I want, they just wont go back, any ideas?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function changeImg(img, newimg) {
img.src = newimg;
}
</script>
<body>
<img onclick="changeImg(this, 'staten_uw.jpg')" src="staten_moored.jpg">
<img onclick="changeImg(this, 'block_uw.jpg')" src="block_moored.jpg">
</body>
</html>
They don't go back because the code always changes it to the _uw images. If you want them to toggle, the function needs to check what image is currently displayed. Something like this:
function changeImg(img) {
if ( img.src.indexOf("_uw") > 0 ) {
img.src = img.src.replace("_uw","_moored");
}
else {
img.src = img.src.replace("_moored","_uw");
}
}
will work if you have 50x2 different images, named "img1_uw.jpg", "img1_moored.jpg", "img2_uw.jpg", "img2_moored.jpg", etc.
If you only have 2 images, but want 50 buttons that each toggle between them, it's easier:
function changeImg(img) {
if ( img.src == "staten_uw.jpg" ) {
img.src = "staten_moored.jpg";
}
else {
img.src = "staten_uw.jpg";
}
}
Other answers have shown this quite simply as well.
Either way, the HTML should change to something like this:
<img onclick="changeImg(this)" src="block_moored.jpg">
You can do this:
window.onload = function() {
images = document.getElementsByTagName("img");
for (i in images) {
images[i].addEventListener("click", function(e) {
var newsrc = this.togglesrc;
this.togglesrc = this.src;
this.src = newsrc;
});
}
};
and then use
<img togglesrc="staten_uw.jpg" src="staten_moored.jpg" />
In your case, you should use only one img tag:
<img onclick="changeImg(this)" src="staten_moored.jpg">
and check logic in your js:
function changeImg(img) {
img.src = (img.src == 'staten_moored.jpg') ? 'block_moored.jpg' : 'staten_moored.jpg';
}

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