Change image in button on click - javascript

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/

Related

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

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

Changing img src on click with javascript

I need to change image when I click on it every time.
I added full path even it's not working.
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
if (imageon.src=="play1.gif"){
imageon.src="shutdown.png";
}
else if (imageon.src== "shutdown.png") {
imageon.src="play1.gif";
}
};
</script>
<img src="shutdown.png" id="myElement" onclick="changeImage();" style="width:95px"></img>
Javascript:
var pullImage=document.getElementById("change");
function changeImage(){
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif") {
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png";
};
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png"){
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif";
}
};
The problem is your path. I recreated the problem and i alerted the actual source which look like this:
You will either have to give the actual full path. Or you dont use the path as refrence, but a html reference. For example a hidden div with value 1 or 2 - for the used image
<div id="imgnumber">1</div>
<script>
var imagediv = document.getElementById("imgnumber");
var imageon= document.getElementById("myImg");
function changeImage(){
if (imagediv.innerHTML == "1"){
imageon.src="b.png";
imagediv.innerHTML = "2";
}
else if (imagediv.innerHTML == "2") {
imageon.src="a.gif";
imagediv.innerHTML = "1";
}
};
</script>
Please use below javascript and place it anywhere below tag you are using
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
var filename = imageon.src.replace( /^.*?([^\/]+)\..+?$/, '$1' );
if (filename=="play1"){
imageon.src="shutdown.jpg";
}
else if (filename== "shutdown") {
imageon.src="play1.jpg";
}
};
</script>
Using attr function you can change src of image :
$("#my_image").attr("src","second.jpg");
You can also create event eg. put thumbnail and on clicking load original image:
$('#my_image').on({
'click': function(){
$('#my_image').attr('src','second.jpg');
}
});

Why is Javascript function not being called?

First Question on this site so I hope I do this right! I have a javascript function that I want to display an image (image1.jpg) when the page is loaded, and then every 2 seconds change the image by going through the loop. However only the first image is showing so it seems the JS function is not being called. Can anyone tell me if I am doing something wrong here because it looks fine to me so can't understand why it won't work. Thanks
<html>
<head>
<script type="text/javascript">
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var i = 1;
if(i>images.length-1){
this.src=images[0];
i=1;
}else{
this.src=images[i];
i++;
}
setTimeout("displayImages()", 2000);
}
</script>
</head>
<body onload="displayImages();">
<img id="myButton" src="image1.jpg" />
</body>
</html>
You need to move the line
var i = 1;
outside the displayImages -function or it will start from one each time!
EDIT: But using a global variable is not considered good practice, so you could use closures instead. Also as noted in other answers, you are referencing this which does not refer to the image object, so I corrected that as well as simplified the logic a bit:
<script type="text/javascript">
function displayImages( i ){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var img = document.getElementById('myButton');
img.src = images[i];
i = (i+1) % images.length;
setTimeout( function() { displayImages(i); }, 2000 );
}
</script>
<body onload="displayImages(0);">
You need the value of i to be available at each call, it can be kept in a closure using something like:
var displayImages = (function() {
var i = 0;
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
return function() {
document.getElementById('myButton').src = images[i++ % images.length];
setTimeout(displayImages, 2000);
}
}());
Also, since this isn't set by the call, it will default to the global/window object, so you need to get a reference to the image. That too could be held in a closure.
There are a couple of issues here that are stopping this from working.
First the var i = 1; needs to be moved outside the function to make the increment work. Also note that the first item in an array is 0, not 1.
Second you're using this to refer to change the image's src, but this is not a reference to the image. The best thing to do is use here is document.getElementById instead.
var i, button;
i = 0;
button = document.getElementById('myButton');
function displayImages() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if (i > images.length - 1){
button.src = images[0];
i = 0;
}
else{
button.src = images[i];
i++;
}
setTimeout(displayImages, 2000);
}
There's still some room for improvement and optimisation, but this should work.
You are reinitializing value of i every time, so change the following:
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(!displayImages.i || displayImages.i >= images.length) displayImages.i = 0;
document.getElementById('myButton').src = images[displayImages.i];
displayImages.i++;
setTimeout(displayImages, 2000);
}
Functions are objects in JS and because of this:
you can pass them by reference and not as a string improving performance and readability
you can add fields and even methods to a function object like I did with displayImages.i
EDIT: I've realized that there was one more issue src was not being set for button.
Now I've fixed this and also made other improvements.
Here is the fiddle http://jsfiddle.net/aD4Kj/3/ Only image URLs changed to actually show something.
<script type="text/javascript">
var i = 1;
function displayImages(){
.......
........
Just make "i" Global. so that whenever displayImages being called it will not redefined to 1.
<html>
<head>
<script type="text/javascript">
var i = 1;
function displayImages() {
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
i++;
if (i > images.length - 1) {
i = 0;
}
$('#myButton').attr('src', images[i]);
setTimeout(displayImages, 2000);
}
</script></head>
<body onload="displayImages();">
<img id="myButton" src="img1.jpg" height="150px" width="150px"/>
</body>
</html>
Make i global.
here your are using displayImages() recursively and variable for index i. e i assign as local variable in function displayImages() , you need to assign it global variable i.e outside of the function also initialize it from i=0 as array index always start from 0,
your code become
var i = 0; // assign i global
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(i>images.length-1){
document.getElementById('myButton').src=images[0]; //get img by id
i=0; // to get first image
}
else{
document.getElementById('myButton').src=images[i]; //get img by id
i++;
}
setTimeout("displayImages()", 2000);
}

Javascript onMouseover to swap images

I have some code that makes an image larger when moused over:
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
}
</script>
and I call those functions with:
<a><img border="0" src="category_icons/addorder.png" onmouseover="bigImg(this)" onmouseout="normalImg(this)"></a>
But what I would really like to do is make it so the bigIMG(x) function also changes the image. I'm not extremely familiar with javascript and was wondering if someone knew what I can code in, to swap the image. The image name is addorder2.png. I've tried using this.src="addorder2.png"; but that is not working.
This will do. Change the image src into "addorder2.png".
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = " addorder.png";
}
</script>
My 2 cents:
LIVE DEMONSTRATION
Don't use inline JS, rather you can set a data.* attribute
and an object literal that will contain your desired changes
and read it with JS:
<img class="zoom" src="img.jpg" data-enlarge='{"src":"img2.jpg", "zoom":"1.2"}'>
As you can see above we'll target with JS every element with class "zoom"
function enlarge(){
var el = this,
src = el.src,
data = JSON.parse(el.dataset.enlarge);
el.src = data.src;
el.style.transition = "0.3s";
el.style.transform = "scale("+data.zoom+")";
el.addEventListener('mouseleave', function(){
el.src = src;
el.style.transform = "scale(1)";
},false);
}
var $ZOOM = document.querySelectorAll('.zoom');
for(var i=0; i<$ZOOM.length; i++){
$ZOOM[i].addEventListener('mouseenter', enlarge, false);
}
With Javascript you can edit the src attribute of the img.
Javascript:
function bigImg()
{
document.getElementById("myImg").src="addorder2.gif";
}
HTML:
<!DOCTYPE html>
<html>
<body>
<img id="myImg" onmouseover="bigImg()" src="addorder.png">
</body>
</html>
I recommend checking out w3schools to learn more about image document manipulation and of course specifically getting and setting the image src element
Just change x.src property according to function:
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "category_icons/addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = "category_icons/addorder.png";
}

Categories