why the following code doesn't perform as expected? - javascript

<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
function myFunction()
{
var img = document.getElementById("image");
if (img.src == "smiley.gif")
document.getElementById("image").src="landscape.jpg";
else
document.getElementById("image").src="smiley.gif";
}
</script>
<button type="button" onclick = "myFunction()"> click me </button>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>
I would like to let the HTML page to switch between two pictures each time user click the button, but the picture never changes.
When I change the
if (img.src == "smiley.gif")
into
if (img.src.match("smiley.gif"))
then the code works as expected.
Could anyone please let me know the reason?

devnull69 is right. If you set the img's source to a relative path, it's src attribute will still return the full URL. You need to either fully qualify the path to the image or strip the img.src value to just the final component (filename) and compare.
For example, you could do:
var imgFilename = img.src.substring(img.src.lastIndexOf("/") + 1);
if (imgFilename === "smiley.gif") {
// Do something.
}

Related

how to change an image source more than once using onclick on html and javascript

I am trying to have an image, once clicked move on to image 2, then once image 2 is clicked it moves on to image 3, then image 4 and so on, but I am struggling to find a way to have more than 2 images? So far I have tried various different ways such as repeating the code I already have, using multiple if statements and switch statement but I just cannot seem to be able to use more than 2 images. I am only a beginner coder so it is difficult to see where I am going wrong. the expected outcome would be just to have a number of images appearing after each one is clicked.
So far the code that I have that's working is:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Social Media</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script type="text/javascript">
var mysrc = "image1.jpg";
function changeImage() {
if (mysrc == "image1.jpg") {
document.images["pic"].src = "image1.jpg";
document.images["pic"].alt = "image1";
mysrc = "image.jpg";
}
else {
document.images["pic"].src = "image.jpg";
document.images["pic"].alt = "image";
mysrc = "image1.jpg";
}
}
</script>
</head>
<body>
<img src="image.jpg"
alt="image" id="pic" class="portrait"
onclick="changeImage()"
width="1000px" height="500px"
style="cursor:pointer">
</body>
</html>
and i have been able to get the same results by doing:
function change() {
var image = document.getElementById('image');
image.src = "image1.jpg"
}
</script>
</head>
<body>
<img src="image.jpg" alt="text" id="image" onclick="change();">
but i just cant seem to get more than 2 images? as mentioned I am just a beginner so I'm really not sure if it's just me making stupid mistakes, any advice would be really helpful
You should be to do this using an array and a simple variable counter.
var imgCount = 0;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"...];
imgCount will get added to every time <img> is clicked.
<script>
var imgCount = -1;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"...];
function change() {
imgCount++;
var image = document.getElementById('image');
image.src = images[imgCount];
}
</script>
<img src="image.jpg" alt="text" id="image" onclick="change()">
The src is now called from the array. imgCount serves as the counter of the amount of times the image has been clicked and is used to find the correct src with the array since it also serves as an index.
If you don't know much about arrays read MDN.
I'm sure that you don't have an endless amount of pictures, so you can also use this:
<script>
var imgCount = -1;
var images = ["img1.png", "img2.png", "img3.png", "img4.png"];
function change() {
if (imgCount !== images.length - 1)
imgCount++;
else
imgCount = 0;
var image = document.getElementById('image');
image.src = images[imgCount];
}
</script>
<img src="image.jpg" alt="text" id="image" onclick="change()">
Now, if <img> is clicked and it is on the last image, it will go back to the beginning. The if statement sees whether or not the counter equals the amount of images in the array. If it hasn't it keeps adding. If it hasn't, it sets the counter back to 0.

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";
}

Changing the src of an image with JavaScript does not cause the image to change

I am trying to toggle an image if I click on it. The JavaScript does seem to replace the image, however, the updated image does not appear on the screen. Here is my HTML code:
<!DOCTYPE html>
<html>
<script src="myscript.js" defer></script>
<div><img id="light" src="images/light_off.png" width="200px"></div>
</html>
and my JavaScript code:
var light_src = document.getElementById('light').src;
var image = light_src.substring(light_src.lastIndexOf("/")+1);
light.addEventListener("click", function(){
if (image == "light_off.png"){
alert("1");
light_src = "file:///H:/mydir/images/light_on.png";
}
else {
alert("2");
light_src = "file:///H:/mydir/images/light_off.png";
}
});
The source does seem to be changing because each time I click on the image, the alert toggles between 1 and 2. However, the image does not appear to change on the screen.
I have verified that both images work by copying the URL into the browser address bar.
What am I doing wrong?
The problem is that you're changing the value of light_src, not the element's source. In other words, light_src is a copy of the source, and changing it does not change the images source.
Instead of storing the source in a variable, you should just store the image element, like this:
// The image URLs
const imageOn = 'file:///H:/mydir/images/light_on.png'
const imageOff = 'file:///H:/mydir/images/light_on.png'
// Store the image element to use later
const imageElement = document.getElementById('light')
// Add the event listener
imageElement.addEventListener("click", function() {
if (imageElement.src === imageOn) {
imageElement.src = imageOff
console.log('Switched light off')
} else {
imageElement.src = imageOn
console.log('Switched light on')
}
});
Dont use .src with the selector
var light=document.getElementById('light');
var image = light.src.substring(light.src.lastIndexOf("/")+1);
light.addEventListener("click", function(){
if (image == "light_off.png"){
console.log(light.src);
light.src = "file:///H:/mydir/images/light_on.png";
}
else {
console.log(light.src);
light.src = "file:///H:/mydir/images/light_off.png";
}
});
<!DOCTYPE html>
<html>
<script src="myscript.js" defer></script>
<div><img id="light" src="images/light_off.png" width="200px" alt="image"></div>
</html>

Add letters to image source through javascript

In my photo gallery I have it so on click of an image it just changes the larger image to the source of it. But now I want the onclick function of the image to take the source that it would originally inject into the image and add 3 letters to the end before injecting, "lrg".
Javascript:
<script type="text/javascript">
function setImg(a){
document.getElementById('ImageFrame').src =
a.getElementsByTagName('img')[0].src
}
</script>
Html image that you click.
<a href="#gallery" onclick="setImg(this);"><img class="gallery" src="JCF/PICT0421.jpg"
/></a>
Larger image that changes:
<div>
<img id="ImageFrame" src="JCF/PICT0422.jpg" width="500" />
</div>
When the link injects into the "imageframe" I want the source to change to JCF/PICT0421lrg.jpg
If i got it right, this will solve our problem.
<script type="text/javascript">
function setImg(a){
var arr = a.getElementsByTagName('img')[0].src.split(".");
document.getElementById('ImageFrame').src = arr[0]+"lrg"+"."+arr[1];
}
</script>
extended example
http://jsfiddle.net/ymutlu/E9Fq5/
In change setImg to
function setImg(a){
var file_parts = a.getElementsByTagName('img')[0].src.split(".");
var new_name = file_parts[0] + "lrg." + file_parts.slice(1).join(".");
document.getElementById('ImageFrame').src = new_name;
}
This will add the "lrg" before the first dot in the filename.

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};​
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>

Categories