Cycling images with javascript - 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";
}

Related

I can't use .src with .pathname in JavaScript

I'm trying to use a code to compare the image's path that is displaying to the relative path independent of the url, but .pathname isn't working
<html>
<head>
<title>change images</title>
<script>
var img=document.getElementById('img').src;
function change(){
if(img.pathname='img1.png'){
var next='img2.png';
document.getElementById('btn').innerHTML='img2.png';
}else if(img.pathname='img2.png'){
var next='img1.png';
document.getElementById('btn').innerHTML='img1.png';
}else{
document.getElementById('btn').innerHTML='error';
}
document.getElementById('img').src=next;
}
</script>
</head>
<body>
<img id='img' src="img1.png">
<button id='btn' onclick="change()">change</button>
</body>
<html>
on console it 'says' that img isn't an object
I tried to look for what img.pathname returns and it returned undefined
Pathname isn't a property of the image element. From looking at your code it's clear you just want the filename of the image, without the path. This will do that for you...
function change() {
// get everything after the last / in the image src attribute
var current = document.getElementById('img').src.split("/").slice(-1);
if (current == 'img1.png') {
var next = 'img2.png';
document.getElementById('btn').innerHTML = 'img2.png';
}
else if (current == 'img2.png') {
var next = 'img1.png';
document.getElementById('btn').innerHTML = 'img1.png';
}
else {
document.getElementById('btn').innerHTML = 'error';
}
document.getElementById('img').src = next;
}
It splits the image src attribute at each instance of / into an array, and then slice cuts it at a specific index, in this case the last element, so that's all you get.
Also, notice the use of == when comparing values. If you have...
if (current = "something)
then it actually sets current to the value "something" (because of the single =) and the if statement evaluates as true.
I found another solution using indexOf() to search for the image name in the .src string.
<script>
function change(){
var img=document.getElementById('img').src;
if (img.indexOf('img1.png')!= -1){
var next='img2.png';
} else if (img.indexOf('img2.png')!= -1) {
var next='img1.png';
} else {
document.getElementById('btn').innerHTML='else';
}
document.getElementById('img').src=next;
document.getElementById('btn').innerHTML=next;
}
</script>

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>

Image swapping when a variable changes

I have an html page that has one image object.
I am trying to write some JavaScript but something isn't working in the script. I have a piece of script that reads a variable and if the variable 'e' is equal to 1, then one image appears. If 'e' is anything other number then image 2 appears. For now, 'e' is static, but it will be dynamic.
How do you change an image dynamically based off a variable?
Any help is most appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<body onload="changei()">
<img id="im1" src="Images/lion1.jpg" width="100" height="180" style="display:show">
<p> hello</p>
<script>
function changei() {
var e = 0;
changei(e);
// something changed e in e = 0;
change(e);
function changei(e) {
var loc = '';
if (image.src.match("lion1")) {
image.src = "Images/lion1.jpg";
} else {
image.src = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
</script>
</body>
</html>
You can use jQuery to change image source. Your function have e inside, pass it as parameter and you can change the image where you want just by calling the function with the corresponding value.
var e = 1;
changei(e);
// something changed e in e = 0;
changei(e);
function changei(e) {
var loc = '';
if (e==1) {
loc = "Images/lion1.jpg";
} else {
loc = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
Example: You can attach an event to an input, keyup and every time you press a key in that input the image will change based on what you entered.
changei(1); // when entering in page set src
$('#eInput').keyup(function(){ // when something was inserted on input
var e = $(this).val();
changei(e);
});
function changei(e) {
var loc = '';
if (e==1) {
loc = "http://images.math.cnrs.fr/local/cache-vignettes/L256xH256/section1-original-0f409.png";
} else {
loc = "http://www.data-compression.com/baboon_24bpp.gif";
}
$('#im1').attr("src",loc); // change image source
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="eInput" />
<img id="im1" src="Images/lion1.jpg" style="display:show">
You can do two things:
You will be changing value of the variable e in some function then simply create a function to change image as follows and call it.
function changeImg(e){
if(e==1)
//your code for image 1
else
//code for image 2
}
Call this function right after you change e.
Use the setInterval() function. e.g.
setInterval(5000,function(){
changeImg(e);
});
Although, you should keep in mind that you need to make e global for case 2

Change image in button on click

I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.
The code I'm using:
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
And the Javascript:
function action() {
swapImage('images/image2.png');
};
var swapImage = function(src) {
document.getElementById("ImageButton1").src = src;
}
Thanks in advance!
While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).
You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)
Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
var tgt = byId('ImageButton1');
tgt.secondSource = 'images/image2.png';
}
function byId(e){return document.getElementById(e);}
function action()
{
var tgt = byId('ImageButton1');
var tmp = tgt.src;
tgt.src = tgt.secondSource;
tgt.secondSource = tmp;
};
function action2()
{
var tgt = byId('imgBtn1');
var tmp = tgt.src;
tgt.src = tgt.getAttribute('src2');
tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
<br>
<button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
</body>
</html>
You need to store the old value in a global variable.
For example:
var globalVarPreviousImgSrc;
var swapImage = function(src)
{
var imgBut = document.getElementById("ImageButton1");
globalVarPreviousImgSrc = imgBut.src;
imgBut.src = src;
}
Then in the action method you can check if it was equal to the old value
function action()
{
if(globalVarPreviousImgSrc != 'images/image2.png')
{
swapImage('images/image2.png');
}else{
swapImage(globalVarPreviousImgSrc);
}
}
It's not a good idea to use global variables in javascripts use a closure or object literal. You can do something like using a closure
(function(){
var clickCounter = 0;
var imgSrc1 = "src to first image";
var imgSrc2 = "src to second image"
functions swapImage (src)
{
var imgBut = document.getElementById("ImageButton1");
imgBut.src = src;
}
function action()
{
if(clickCounter === 1)
{
swapImage(imgSrc1);
--clickCounter;
}else{
swapImage(imgSrc2);
++clickCounter;
}
}
})();
(I haven't run this code though)
This nice w3documentation gives you best practices.
Check this a working example just copy paste and run-
HTML
<button onClick="action();">click me<img src="http://dummyimage.com/200x200/000000/fff.gif&text=Image+1" width="200px" id="ImageButton1"></button>
JAVASCRIPT
<script>
function action()
{
if(document.getElementById("ImageButton1").src == 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1' )
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/dec4ce/fff.gif&text=Image+2';
else
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1';
}
</script>
Check this working example - http://jsfiddle.net/QVRUG/4/

JavaScript Photo Slider

I'm working on making a JS script that will go in the header div and display a few pictures. I looked into JQuery Cycle, but it was out of my league. The code I wrote below freezes the browser, should I be using the for loop with the timer var?
<script type="text/JavaScript" language="JavaScript">
var timer;
for (timer = 0; timer < 11; timer++) {
if (timer = 0) {
document.write('<img src="images/one.png">');
}
if (timer = 5) {
document.write('<img src="images/two.png">');
}
if (timer = 10) {
document.write('<img src="images/three.png">');
}
}
</script>
Thanks!
Assuming you want a script to rotate images and not just write them to the page as your code will do, you can use something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="target"></div>
<script>
var ary = ["images/one.png","images/two.png","images/three.png"];
var target = document.getElementById("target");
setInterval(function(){
target.innerHTML = "<img src=\""+ary[0]+"\" />";
ary.push(ary.shift());
},2000);
</script>
</body>
</html>
Of course the above code has no effects (like fading) which jQuery will give yous, but it also doesn't require loading the entire jQuery library for something so basic.
How about just running the script after the page loads?
<script>
// in <head> //
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
}
</script>
Then use <body onload="load();"> to run the script.
Edit
To add in a delay loading images, I rewrote the code:
<script>
// in <head> //
var displayOnLoad = true; // Set to true to load the first image when the script runs, otherwise set to false to delay before loading the first image
var delay = 2.5; // seconds to delay between loading images
function loadImage(url) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
setTimeout(loadImage(images[i]), (i+displayOnLoad)*(delay*1000));
}
}
</script>
Set displayOnLoad = false; if you want to wait the specified delay before loading the first image. The delay is set in seconds. I recommend waiting over a single second between images, as they may take some time to download (depending on the user's internet speed).
As with the first snippet, I haven't tested the code, so please tell me if an error occurs, and I will take a look.
Since you used the jquery tag on your question, I assume you are OK with using jQuery. In which case, you can do something like this:
In your static HTML, include the img tag and set its id to something (in my example, it's set to myImg) and set its src attribute to the first image, e.g.:
<img id="myImg" src="images/one.png">
Next, use jQuery to delay execution of your script until the page has finished loading, then use setTimeout to create a further delay so that the user can actually spend a few seconds looking at the image before it changes:
<script>
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
$(function() {
// Document is ready
setTimeout(function() {
// We will get here after the first timer expires.
// Change the image src property of the existing img element.
$("#myImg").prop("src", "images/two.png");
setTimeout(function() {
// We will get here after the second, nested, timer expires.
// Again, change the image src property of the existing img element.
$("#myImg").prop("src", "images/three.png");
}, imgTimeoutMsecs);
}, imgTimeoutMsecs);
});
</script>
Of course, that approach doesn't scale very well, so if you are using more than three images total, you want to modify the approach to something like this:
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
// Array of img src attributes.
var images = [
"images/one.png",
"images/two.png",
"images/three.png",
"images/four.png",
"images/five.png",
];
// Index into images array.
var iCurrentImage = 0;
function cycleImage() {
// Increment to the next image, or wrap around.
if (iCurrentImage >= images.length) {
iCurrentImage = 0;
}
else {
iCurrentImage += 1;
}
$("#myImg").prop("src", images[iCurrentImage]);
// Reset the timer.
setTimeout(cycleImages, imgTimeoutMsecs);
}
$(function() {
// Document is ready.
// Cycle images for as long as the page is loaded.
setTimeout(cycleImages, imgTimeoutMsecs);
});
There are many improvements that can be made to that example. For instance, you could slightly simplify this code by using setInterval instead of setTimer.
The code you've provided simply iterates through the for loop, writing the images to the browser as it does so. I suggest you take a look at JavaScript setTimeout function.
JS Timing

Categories