JS Image onClick src problems - javascript

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().

Related

How to toggle images using file paths in 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">

Image src relative path to absolute path

I have website and now making a hybrid app for it.
I get all my blog post using Jquery get method.
However the issue is that <img src="/media/image.png"> is sometime relative url and sometime an absolute url.
Everytime an absolute url breaks the image showing 404 error.
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
Note: I need to change images present only in <div id="details"> div.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
You can use common function or image onload to rerender but I h
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
document.querySelectorAll('#details img').forEach(img => {
const src = img.getAttribute('src');
// use regex, indexOf, includes or whatever to determine you want to replace the src
if (true) {
img.setAttribute('src', 'https://www.example.com' + src);
}
});
The best would be to do this with the response html from the ajax request before inserting into the main document so as to prevent needless 404 requests made while changing the src
Without seeing how you are making your requests or what you do with the response here's a basic example using $.get()
$.get(url, function(data){
var $data = $(data);
$data.find('img[src^="/media/"]').attr('src', function(_,existing){
return 'https://www.example.com' + existing
});
$('#someContainer').append($data)'
})
You can just get all the images from an object and find/change them if they don't have absolute url.
var images = $('img');
for (var i = 0 ; i < images.length ; i++)
{
var imgSrc = images[i].attributes[0].nodeValue;
if (!imgSrc.match('^http'))
{
imgSrc = images[i].currentSrc;
console.info(imgSrc);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/test.jpg">
<img src="/media/test.jpg">
<img src="https://www.example.com/media/test.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>

Changing multiple images source using jquery (and some other thing as well)

I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.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"));
}

Categories