Change button image onclick - javascript

I have this code to change from image 1 to image 2. How can I make it change from image 2 to image 3, and back to image 1? Thanks
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()"><img id="myImg" src="image1.gif" width="107" height="98"></button>
<script>
function myFunction()
{
document.getElementById("myImg").src="image2.gif";
}
</script>
</body>
</html>

http://jsfiddle.net/9R2J7/1/
var img_array = ['http://placehold.it/100x100/green', 'http://placehold.it/100x100/blue', 'http://placehold.it/100x100/red'];
i = 0;
function myFunction() {
i++;
document.getElementById("myImg").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}

You could do
function myFunction()
{
if( document.getElementById("myImg").src == "image1.gif" ){
document.getElementById("myImg").src = "image2.gif";
}
elseif( document.getElementById("myImg").src == "image2.gif" ){
document.getElementById("myImg").src = "image3.gif";
}
else{
document.getElementById("myImg").src = "image1.gif";
}
}
It's not very elegant, but it could be a solution.
Kind regards.

Using jQuery.
change your html to something of the sort:
<button id="change-img"><img ... /></button>
Then you can add an onclick to the #change-img element. In your jQuery, add
$('#change-img').click(function() {
var image = $('#myImg');
var imgNum = image.attr('src').split('.')[0].replace('image', ''); // gets the number
imgNum = (imgNum % 3) + 1;
image.attr( { 'src' : 'image' + imgNum + '.gif' } ); // selects image, changes source
});
And there you have it.
Made a demo, similar to what you'd like to achieve: http://jsfiddle.net/94VKa/.

One further approach:
// initialise the array, using array-literal syntax:
var img_array = ['http://placehold.it/100x100/green',
'http://placehold.it/100x100/blue',
'http://placehold.it/100x100/red'];
function myFunction() {
// finding where in the 'img_array' the current src is to be found:
var current = img_array.indexOf(this.src);
// updating the src of the clicked element, to either the next element in
// the array (if 'current + 1' does *not* evaluate to equal the length of the
// array, or to the first element in the array if 'current + 1' *does* equal
// the length of the array:
this.src = img_array[current + 1 === img_array.length ? 0 : current + 1];
}
// getting a reference to the element to click on,
// add an event-listener to 'listen' for that event, and execute the
// named function:
document.getElementById('myImg').addEventListener('click', myFunction);
JS Fiddle demo.
References:
Array.prototype.indexOf().
Conditional ('ternary') operator.
document.getElementById().
EventTarget.addEventListener().

Related

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 to toggle between two images with a button using Javascript code?

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);

Appending in the middle of a src attribute of Image in Jquery

I have a bit of code which I want to add just the letters "mb" at the beginning of the name of my image file using JQuery. This is quite green to me so I ask for your forgivness of my naivety in advabce. An example of what I am seeking to do is switching my image name from "images/folder/photo.jpg" to "images/folder/mb_photo.jpg". The images I plan to use already in classes so I have the mock up for selecting those classes already layed out. I am just stuck on how to insert in the middle of the image tag.
As requested, what I have so far is:
$(window).resize(function(){
if ($('#content').width() < 700 ){
$('#photos_member').;
$('#photos_group').;
}
});
Thank you guys in advance for your help.
This should do what you need...
function updateImageSrc(add) {
if (add === true) {
$("img.photos_member:not(.src-modified), img.photos_group:not(.src-modified)")
.attr("src", function() {
var split = this.src.split("/");
split[split.length - 1] = "mb_" + split[split.length - 1];
return split.join("/");
})
.addClass("src-modified");
}
else {
$("img.photos_member.src-modified, img.photos_group.src-modified")
.attr("src", function() {
var split = this.src.split("/");
split[split.length - 1] = split[split.length - 1].substr(3);
return split.join("/");
})
.removeClass("src-modified");
}
}
And to call it in a window resize handler, do this...
$(window).resize(function() {
if ($("#content").width() < 700) {
updateImageSrc(true);
}
else {
updateImageSrc(false);
}
});
use like
<img id="test" src="images/folder/photo.jpg"/>
<input type="button" id="btn" value="change src"/>
$("#btn").click(function(){
var newSrc=$("#test").attr("src").split("/");
newSrc[newSrc.length-1]="mb_"+newSrc[newSrc.length-1];
$("#test").attr("src",newSrc.join());
});
DEMO
Use the replace method.
var img = "images/folder/photo.jpg";
var newImg = img.replace(/\/(\w+.jpg)/, "/mb_$1");
newImg would contain the updated filename("images/folder/mb_photo.jpg")

Javascript slideshow with caption issues

So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />

change image using javascript based on function result

I've been searching and trying to figure this out for hours but i seem to be missing something. Basically i'm trying to make it so if i click a link/button it executes a script to increase or decrease the number by a specified amount in a function. (in this example its by 1)
The image files that im trying to display are supposed to change depending on the final result. but the image never changes.
any suggestions are greatly appreciated
<script type="text/javascript">
var p1hps = 20;
var p1hpimage
function p1p1Click() {
p1hps = (p1hps +1);
function p1health(){
};
}
function p1health() {
p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1health();
}
</script>
<body>
<img src="images/p1p1.png" width="165" height="87" alt="">
<img src="images/p120.png" id="p1hp" width="324" height="252" alt="">
</body>
You need to invoke the p1health function inside p1p1Click, instead you were declaring another function with the name p1health inside p1p1Click.
Also the images src property, you need to assign the value of the variable p1hpimage instead of recursively calling the p1health method
var p1hps = 20;
function p1p1Click() {
p1hps++;
p1health();
}
function p1health() {
var p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1hpimage ;
}
Demo: Fiddle -- inspect the source with dev tools to see the src getting updated
Try this :
var _myPicArray =new Array("pic1.png","pic2.png","pic3.png");
function p1health(n) {
document.getElementById('p1hp').src = myPicArray[n] ;
}

Categories

Resources