Changing img src on click with javascript - 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');
}
});

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>

How to toggle images

I am a programming fool,
All I need is to be able to toggle two images, one which acts as the 'up state' of a button and then 'onclick' the second image appears and remains until it is clicked again whereby it is replaced by the the 'upstate image'.
Please don't mock me for this pitifull attempt which fails miserably. Here is my code.
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change()"/>
Thank you in anticipation.
Check this demo.
function change(image) {
if (image.src.indexOf("imgd1.svg") > -1){
image.src ="imgd1over.svg";
}
else{
image.src ="imgd1.svg";
}
}
In the fiddle case the image.src wasn't just the image's name, but the full url: http://fiddle.jshell.net/_display/imgd1.svg. So I have used indexOf() to check if the image's source constains the string you want.
Besides, I have changed the way change() function references to the image:
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change(this)"/>
Using change(this) will set the own image as the first parameter of the event, so you don't need to get it in the window object or event with getElementById or whatever.
function change() {
var image = document.getElementById("test");
if (image.src.indexOf("imgd1.svg") > -1 ){
image.src = "imgd1over.svg";
}
else if(image.src.indexOf("imgd1over.svg") > -1 ){
image.src = "imgd1.svg";
}
}
Here is the working code:
<img src ="imgd1.svg" name="pic" onclick="change();"/>
<script>
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
}
<script>
See the full demo:
http://jsfiddle.net/jswsze5q/
Try this:
<script>
function change() {
var img1 = "imgd1.svg",
img2 = "imgd1over.svg";
var imgElement = document.getElementById('test');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
</script>
<img src="imgd1.svg" id="test" onclick="change();"/>
Example: jsfiddle
Try using Jquery
var flag = 0;
function change(){
if(flag){
$("#img").attr("src","img1.png");
flag = 0;
}
else{
$("#img").attr("src","img2.png");
flag = 1;
}
}
Simplest toggle option
where variable flag acts as flag which detects which image is active
img is the id of image control.
Code to include Jquery from google CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

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

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 BG Image Change

My site has a background that looks cool, but might impair usability (and it burns if you look at it too long) so I want a link that changes/removes background image with javascript. I've googled it, but can't find something that works.
Is there a way to make a link like [a href="javascript:???????"]remove bg[/a]?
If your background image is NOT specified in the body tag.
<script type="text/javascript">
var img = document.getElementById('your image ID');
var shown = true;
function toggleImg(){
if(shown == true){
img.style.display = "none";
shown = !shown;
}else{
img.style.display = "";
shown = !shown;
}
}
</script>
If your background image is specified in the body tag.
<script type="text/javascript">
var imgSrc = "your image source"
var shown = true;
function toggleImg(){
if(shown == true){
document.body.background = "";
shown = !shown;
}else{
document.body.background = imgSrc;
shown = !shown;
}
}
 
remove bg
function removeBackgroundImage()
{
document.body.background = "";
}
Change Background
Since you don't tell us how you put in your background image (ie. the html/css markup) it's difficult to give you an accurate answer.
javascript:var f=eval("document.getElementsByTagName('BODY')[0].style.backgroundImage='inherit';");
You could use jQuery CSS function.
$('#removebg').click(function(){
$('body').css("backgroundImage","yoururl");
});
<a id="removebg">removebg</a>
http://api.jquery.com/css/

Categories