Image swapping when a variable changes - javascript

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

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>

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>

How to add while loop to randomizer

I am trying to learn JavaScript and have made a website which randomizes gifs onclick from an array.
What I would like to do now is insert a while loop so that it will compare the currentgif to the next randomized image so no duplicates are shown but I can't quite figure out what I am doing wrong, most likely a syntax issue.
HTML
<!DOCTYPE html>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/rand.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<head>
<title>Randomizer</title>
</head>
<body>
<p>This image is random</p>
<a href="#" class="click">
<section>
<img>
<script>
getRandomImage()
</script>
</img>
</section>
</a>
</body>
</html>
JavaScript
var randomImage = new Array();
randomImage[0] = "images/1.gif";
randomImage[1] = "images/2.gif";
randomImage[2] = "images/3.gif";
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomImage.length);
$(this).html('<img src="'+randomImage[number]+'" />');
});
});
You first need to get which image it is:
function returnImgNum(){
var imgNum = parseInt($('img').attr('src').split("/")[1].replace('.gif', ""));
return imgNum;
}
Then make a loopable function (or just make a while loop, I like doing it this way)
function placeRand(number){
if(number != returnImgNum()){
document.write('<img src="'+randomImage[number]+'" />');
} else {
placeRand(number){
}
}
Then add that comparator loop to your function:
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
placeRand(number);
}
var random_images_array = ['smile.gif', 'frown.gif', 'grim.gif', 'bomb.gif'];
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
Check out this link. It tells you everything you need to know.
http://www.dyn-web.com/code/basics/random_image/random_img_js.php
Create array, put inside all image names (or their indexes if it's better for you) and then use something like this:
var images = ["/first.png", "/second.png", "/third.png", "/fourth.png", "/fifth.png"];
function takeImage() {
// if there is no more images in array, do something or return placeholder image
//if (!images.length) doSomething();
var image = images.splice(Math.floor(Math.random() * images.length), 1);
return image[0];
}
Basically, this function on each call will return one random image name (or index if you want) until there will be no images left in this array.
Simple, you save the last image out of the function. This makes a global variable. A global variable is a variable that exists in all functions, as a local variable only exists in the function itself (other functions cant use it).
// Define it outside of the function so the next time the called
// function gets it still has a value:
var lastNumber=0;
var imagesLength = randomImage.length; // don't recalc the amount of images every time
function getRandomImage(){
var number=0; // start a local variable
while( number == lastNumber){
number = Math.floor(Math.random()*imagesLength );
}
document.write('<img src="'+randomImage[number]+'" />');
}
To expand a bit on the local/global variables, lastNumber is global and can therefor be accessed in the function. var number however is local, it only exists in the function, console.log(number); outside the function would be undefined
To make a suggestion for improvement, document.write is best to be avoided. Browsers don't like them (*can't find doc's to support, feel free to edit), pre-create an image, even if its blank:
<img id="RandomImage" src="transparant.png" />
Now you make a global variable (this can only be done if the javascript is loaded after the image in the source, or with a document ready) to store the image, and use that:
// save reference to image, global (before the function):
var Image2Random = document.getElementById('RandomImage');
// place this instead of the document write.
Image2Random.src = randomImage[number];
This will be a lot faster. Javascript now knows what image to change, it doesn't have to create a new one every call (inserting elements to the DOM is expensive in resources), and the .src is really fast to change just the source.

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/

Categories