How to toggle between two images with a button using Javascript code? - javascript

I have an HTML document that has an image, and I want to click a button to
toggle between the color version and the black & white version. My
javascript code is as follows is below. I realize this question has been
answered before, but the answers were unclear. Questions: Is the IF condition valid? If not, what can I use? Can one compare an image.src with an address on my computer as typed below? Note that nothing is changing when I click. The color image remains.
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.src == "Rondout.jpg") { // I tried three === but that
// didn't work either.
colorImage.src = "Rondout(B&W).jpg";
}
else {
colorImage.src = "Rondout.jpg";
}
}
button2.addEventListener("click", changeToBW);
A portion of my HTML code that's within the body below:
<img id = "colorImage" class = "image" src = "Rondout.jpg">
<button id = "button2" type = "button">Change to B&W</button>

I copied your code to see where the problem is. I used 2 imgs that i just downloaded form google: img1.png and img2.jpeg
It didn't worked. So I opened the DevTab of Google Chrome.
So my code:
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.src == "img1.png") { // colorImage.src = file:///D:/Kokal/Code/JsTests/img1.png
colorImage.src = "img2.jpeg";
}
else {
colorImage.src = "img1.png";
}
}
button2.addEventListener("click", changeToBW);
The problem is that colorImage.src holds the absolute path to the file. So you never end-up in the if you aways go in the else.
Also you want to change the attribute src not the property. So you need to read the attr too. The way to do it is with the function getAttribute('src') on the colorImage.
After that you will need to set that attr with setAttribute('src', [new value])
If something is not clear chek my code below.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<img id = "colorImage" class = "image" src = "./img1.png">
<button id = "button2" type = "button">Change to B&W</button>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
JS:
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
if (colorImage.getAttribute('src') === "./img1.png") {
colorImage.setAttribute('src', "./img2.jpg");
}
else {
colorImage.setAttribute('src', "./img1.png");
}
}
button2.addEventListener("click", changeToBW);

You can use the data attribute to keep track of which image is displayed.
In my example, I use the data attribute data-color for this.
Then in the onClick handler, I get the data-color value and toggle between the 0 and 1. The 1 and 0 then correspond with the index in the array images. Which is added to the src of colorImage.
Here's a working example.
let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
function changeToBW() {
var images = [
"https://images.pexels.com/photos/57905/pexels-photo-57905.jpeg",
"https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg"
];
var imageNum = parseInt(colorImage.dataset.color);
var nextImg = imageNum === 0 ? 1 : 0;
colorImage.src = images[nextImg];
colorImage.dataset.color = nextImg;
}
button2.addEventListener("click", changeToBW);
<img id="colorImage" data-color="0" class="image" src="https://images.pexels.com/photos/57905/pexels-photo-57905.jpeg" width="200">
<div><button id="button2" type="button">Change to B&W</button></div>

let colorImage = document.getElementById("colorImage");
let button2 = document.getElementById("button2");
let imgFlag = 1;
function changeToBW() {
if (imgFlag) {
colorImage.setAttribute('src', "./img2.jpg");
ImgFlag = 0;
}
else {
colorImage.setAttribute('src', "./img1.png");
ImgFlag = 1;
}
}
button2.addEventListener("toggle", changeToBW);

Related

Changing the innerHTML of a certain element when a special picture of a randomised array appears

I want to change the innerHTML of button1 when the picture ('/robot.svg') appears. The logic works fine when I comment out the if-clause, however I can't make the if-clause work.
<img src="/closed_door.svg" alt="closed_door" id="1">
<button id="button">Good luck</button>
let links = ['/beach.svg', '/robot.svg', '/space.svg']
let pic1 = document.getElementById("1")
let button1 = document.getElementById("button")
button1.onclick = function () {
pic1.src = links[Math.floor(Math.random()*3)]
if (pic1.src === '/robot.svg') {
button1.innerHTML = 'game over';
}
}
Thanks for reading or even helping a beginner out!
You need to parse the image name from the src when comparing:
let links = ['/beach.svg', '/robot.svg', '/space.svg']
let pic1 = document.getElementById("1")
let button1 = document.getElementById("button")
button1.onclick = function () {
pic1.src = links[Math.floor(Math.random()*3)];
let name = (pic1.src).substring((pic1.src).lastIndexOf("/"));
console.log(name);
if (name === '/robot.svg') {
button1.innerHTML = 'game over';
}
}
<img src="/closed_door.svg" alt="closed_door" id="1">
<button id="button">Good luck</button>

Is there a way to switch images src back to original after on.click src change event?

I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.

How can I swap between two images on infinite clicks?

How can I swap between two images on infinite clicks (not once) using JS or jQuery
$("button").click(function(){
$("img").attr("src","The New SRC");
});
This code works, but just once.
Try this
var q = 0;
function swapImage() {
if (q == 0) {
document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1562102010-558d6be6268e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
q++;
} else {
document.getElementById("image").setAttribute('src', 'https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
q--;
}
}
<img id="image" src="https://images.unsplash.com/photo-1567095740613-beef70b7e61c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" onclick="swapImage();" />
Let make this simple as possible swap the src and data-src on click.
$('.changeSrc').on('click', function(e){
let src2= $('#img').data('src2');
$('#img').data('src2', $('#img').attr('src'));
alert(src2);
$('#img').attr('src', src2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img" src="./images/img1.jpg" data-src2="./images/img2.jpg"/>
<button class="changeSrc">Change Picture</button>
If by "forever" you mean your user will always see the same image once he's changed it, you need to store that information somewhere. Here's an example where you store the image source in the browser's local storage and read that to set the src property of the image element:
<p>
<img id="my-img" src="">
</p>
<button onclick="changeImage()">
Change image
</button>
<script>
const myImg = document.getElementById("my-img")
const googleLogo = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
const duckduckgoLogo = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png"
const changeImage = () => {
if(myImg.src === googleLogo) {
myImg.src = duckduckgoLogo
localStorage.setItem("img-src", duckduckgoLogo)
} else {
myImg.src = googleLogo
localStorage.setItem("img-src", googleLogo)
}
}
const getImageSrc = () => {
const loadedSrc = localStorage.getItem("img-src")
if(loadedSrc == null) {
myImg.src = googleLogo
} else {
myImg.src = loadedSrc
}
}
getImageSrc()
</script>
Note: The code is correct but it doesn't work in the snippet because I'm reading from localStorage and this seems to be not allowed inside a snippet.

Javascript Image toggle/switcher triggered with a button: How can I get the button text to change

So I have been in the process of having an image switcher to toggle images. What I am doing is having 2 images of the same size that are displaying a clean and labeled version. Simple right? Here is what I have so far:
<button id="button-switch"> Hide/Show Redlines</button><script>(function()
{'use strict';function init(){var el=document.getElementById('deconstructed');
document.getElementById('button-switch').onclick=function(){el.id=='deconstructed'?(el.id='t-b',el.
// PLACE CLEAN IMAGE HERE //////////////
src='_images/clean_image.png',el.alt='my t-b'):(el.id='deconstructed',el.
// PLACE *LABELED* IMAGE HERE //////////////
src='_images/labeled_image.png',el.alt='my deconstructed');}}window.addEventListener('load',init,false);})();</script>
<!-- PLACE *LABELED* ONE MORE TIME HERE
--> <div><img id="deconstructed"
src="_images/labeled_image.png"
alt="my deconstructed"></div>
In this code, the text on the button is the same. I by no means are decent at Javascript and I am amazed I was able to get this series of things to cooperate. Any pointers?
Hi firstly write clean code so that everyone understands.
<input type='button'
id="button-switch"
value='Hide/Show Redlines' / >
<script>(function () {
'use strict';
function init() {
var el = document.getElementById('deconstructed');
var button = document.getElementById('button-switch');
button.onclick = function () {
el.id == 'deconstructed' ? (el.id = 't-b', el.src = '_images/clean_image.png', el.alt = 'my t-b',
button.value = 't-b'
)
: (el.id = 'deconstructed', el.src = '_images/labeled_image.png', el.alt = 'my deconstructed',
button.value = ' Hide/Show Redlines');
}
}
window.addEventListener('load', init, false);
})();
</script>
< !--PLACE * LABELED * ONE MORE TIME HERE -- >
< div > < img id = "deconstructed" src = "_images/labeled_image.png" alt = "my deconstructed" > < / div >
hope this helps...

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

Categories

Resources