How to toggle images using file paths in Javascript? - javascript

I'm trying to change the image shown when a button is clicked.
function change() {
if (document.getElementById("toggle").src == "/folder/original.jpg") {
document.getElementById("toggle").src = "/folder/new.jpg";
} else {
document.getElementById("toggle").src = "/folder/original.jpg";
}
}
<button onclick="change()">Click</button>
<img id="toggle" src="/folder/original.jpg">
I've tried it with a url to check if my code works and it does. When using file paths, the image shown is /folder/original.jpg but doesn't change. I've inspected the element and there are no errors when I click on button. I've also tested to see if /folder/new.jpg would render and it does. Why doesn't it work when I use file paths?

You're checking the src property of the image which will be the full path of the image, to use check the exact path you set the attribute you have to check against the image attribute.
function change() {
if (document.getElementById("toggle").getAttribute('src') == "/folder/original.jpg")
{
document.getElementById("toggle").setAttribute('src', "/folder/new.jpg");
}
else
{
document.getElementById("toggle").setAttribute('src', "/folder/original.jpg");
}
}

You can do it with some regex to get the file name
function change() {
var imgSrc = document.getElementById("toggle").src;
var filename = imgSrc.replace(/^.*[\\\/]/, '');
if (filename == "original.jpg")
{
document.getElementById("toggle").src = "/folder/new.jpg";
}
else
{
document.getElementById("toggle").src = "/folder/original.jpg";
}
console.log(filename);
}
<button onclick="change()">Click</button>
<img id="toggle" src="/folder/original.jpg">

Update: You can check if the src value ends with the path.
function change() {
const img = document.getElementById("toggle");
if (img.src.replace(/\\/g, '/').endsWith('/folder/original.jpg')) {
img.src = "/folder/new.jpg";
} else {
img.src = "/folder/original.jpg";
}
}
<button onclick="change()">Click</button>
<img id="toggle" src="./folder/original.jpg">
If the actual src is the path on the file system, then it will look like this in WIndows:
file:///C:\folder\original.jpg
You can check if it matches using:
const src = 'file:///C:\\folder\\original.jpg';
const isEqual = src.replace(/\\/g, '/').endsWith('/folder/original.jpg');
console.log(isEqual); // true
Here is an example using absolute paths:
const images = [
'http://placekitten.com/240/120',
'http://placekitten.com/200/120'
];
function change() {
const img = document.getElementById('toggle');
let index = images.indexOf(img.src);
if (index === -1) index = images.length - 1;
const nextIndex = (images.length + index + 1) % images.length;
img.src = images[nextIndex];
}
body > button { display: block; }
<button onclick="change()">Click</button>
<img id="toggle" src="http://placekitten.com/240/120">

Related

i want to flip between two images by clicking on the image itself using javascript

i want to flip between two images by clicking on the image itself. help me with the code(i want the most simplified answer, very new learner)
function changeImage(){
var img = document.createElement('img')
img.src =="images/pic2.jpg"
let displayImage = document.getElementById('first')
if (displayImage.getAttribute("src") =="images/pic.jpg") {
document.getElementById('first').appendChild(img);
}
}
You can just change the src attribute of the image.
function switchImage () {
let element = document.getElementById("myImg")
if (element.src == "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg") {
element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Aquilegia_vulgaris_100503c.jpg/420px-Aquilegia_vulgaris_100503c.jpg"
} else {
element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg"
}
}
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg" onclick="switchImage()" />

toggle image via onclick issue javascript

I am trying to toggle between two images I have in a folder via an onclick function. Currently my code does not toggle the image and I am getting no console errors, so I don't know why the toggle is not occurring. my folders look like this:
program-01
program01.index
program01javascript
program01script.js
program01css
images
LightOff.png
LightOn.png
HTML
<div>
<img src="images/LightOff.png" id="light" onclick="DateTime(); imageSwap();" />
<p id="date_time"></p>
</div>
Javascript
function imageSwap(){
var img = document.getElementById("light") ;
if (img.src == "images/LightOff.png"){
img.src = "images/LightOn.png";
} else {
img.src = "images/LightOff.png";
}
}
I believe it has have something to do with my file path and or something to do with the .src property, but unsure of exactly what the issue is.
How about this ?
img.src will return absolute url, I would suggest you to play with the flags instead of image src
var status = false;
function imageSwap() {
var img = document.getElementById("light");
if (!status) {
img.src = "images/LightOn.png";
status = true;
} else {
img.src = "images/LightOff.png";
status = false;
}
}
Or doing it your way, use getAttribute
function imageSwap(){
var img = document.getElementById("light") ;
if (img.getAttribute('src') == "images/LightOff.png"){
img.src = "images/LightOn.png";
} else {
img.src = "images/LightOff.png";
}
}

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

How can I check if the href path contain image or someother link using javascript or jquery?

Any One Know Tell me the suggestion to do this. How can i check if the anchor href attribute contain image path or some other path.
For Example:
<img src="image.jpg"/>
<img src="image.jpg"/>
See the above example shows href attribute contain different path like first one is the image and second one is the some other site link. I still confuse with that how can i check if the href path contain the image path or some other path using jquery or javascript.
Any suggestion would be great.
For example (you may need to include other pic formats if needed):
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
console.log(href_value + " is a pic");
} else {
console.log(href_value + " is not a pic");
}
});
Jquery:
$(document).ready( function() {
var checkhref = $('a').attr('href');
var image_check = checkhref.substr(checkhref.length - 4)
http_tag = "http";
image = [".png",".jpg",".bmp"]
if(checkhref.search("http_tag") >= 0){
alert('Http!');
//Do something
}
if($.inArray(image_check, image) > -1){
alert('Image!');
//Do something
}
});
you may check if image exists or not, without jQuery
Fiddle
var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);

JS Image onClick src problems

First post here.
So I am pretty good with my HTML and PHP, but fail at JS.
I am trying to make a simple toggle using images.
HTML:
<img src="clear.png" id="imgClickAndChange" onclick="changeImage()">
JS:
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "clear.jpg")
{
document.getElementById("imgClickAndChange").src = "full.jpg";
}
else
{
document.getElementById("imgClickAndChange").src = "clear.jpg";
}
}
This code does not work as the script is receiving the src as its full path and not just "clear.jpg".
Not a clue how to get around this.
I've tried using substr, that didn't work.
I wouldn't mind using the full path but the location could be relative on my server.
Rhys
var imgClickAndChange = document.getElementById("imgClickAndChange");
if (imgClickAndChange.src.indexOf("clear.jpg") !== -1){
imgClickAndChange.src="full.jpg"
}else{
imgClickAndChange.src="clear.jpg"
}
First off, you have clear.png in your html snippet, but are checking for clear.jpg in your javascript. After you get that cleared up...
You can use the getAttribute method to check for the "raw" contents of the attribute:
document.getElementById("imgClickAndChange").getAttribute('src'); // clear.png
Or you can use indexOf, as #manraj82 suggests, to check if "clear.jpg" exists in imgClickAndChange's src property:
document.getElementById("imgClickAndChange").src.indexOf("clear.jpg") // numeric index of "clear.jpg" or -1 if not found
Use a regular expression or split to get the section of the URL after the last / and compare that to the value you are testing against.
Alternatively, test with indexOf.
You can inject a flag to HtmlElement to store the state.
var img = document.getElementById('toggle_img');
img.onclick = function()
{
img.src = img.isOff ? 'on.png' : 'off.png';
img.isOff = !img.isOff;
}
See it in action on jsfiddle
I'd suggest the following:
function changeImage () {
var img = document.getElementById('imgClickAndChange'),
src = img.src;
img.src = src.indexOf('clear') > -1 ? 'full.png' : 'clear.png';
}
JS Fiddle demo.
Or:
function changeImage() {
var img = document.getElementById('imgClickAndChange'),
src = img.src;
img.src = src.replace(/(clear)|(full)/, function (a) {
return a == 'clear' ? 'full' : 'clear';
});
}
JS Fiddle demo.
To make it a little more easily-extensible (allowing you to pass in any img element, and using an arbitrary length of images/URLs to toggle between):
function changeImage(el) {
var self = el,
src = self.src,
toggleBetween = self.getAttribute('data-images').split(',');
for (var i = 0, len = toggleBetween.length; i < len; i++) {
if (src.indexOf(toggleBetween[i]) > -1) {
self.src = (i + 1 == len ? toggleBetween[0] : toggleBetween[i + 1]) + '.png';
}
}
}
Using the HTML:
<img src="clear.png" id="imgClickAndChange" data-images="clear,full,arbitrary,other,images" onclick="changeImage(this)" />
JS Fiddle demo.
And, finally, to remove the onclick event-handler, binding the event-handling in the script, rather than in the element itself to reduce the use of obtrusive (and difficult to maintain) JavaScript:
function changeImage(el) {
var self = this,
src = self.src,
toggleBetween = self.getAttribute('data-images').split(',');
for (var i = 0, len = toggleBetween.length; i < len; i++) {
if (src.indexOf(toggleBetween[i]) > -1) {
self.src = (i + 1 == len ? toggleBetween[0] : toggleBetween[i + 1]) + '.png';
}
}
}
var elem = document.getElementById('imgClickAndChange');
elem.addEventListener('click', changeImage);
<img src="clear.png" id="imgClickAndChange" data-images="clear,full,arbitrary,other,images" />
JS Fiddle demo.
References:
Element.getAttribute().
JavaScript Regular Expressions.
String.indexOf().
String.split().
String.replace().

Categories