I can't use .src with .pathname in JavaScript - 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>

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

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>

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

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