Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm using the function below to rotate images on click into the #home-image div, beginning with the first image.
Javascript:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
}
});
HTML:
<img id="home-image" src="img1_on.jpg" />
But
I want to "echo" the file name of the image being displayed, so the viewer sees the name of the image.
How would I "echo" the name of the image into another div, i.e. <div id="home-image-name"></div>?
This is an attempt to echo the output of src into the home-image-name div, but it doesn't work:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("#home-image-name").innerHTML = output;
}
});
This works, with the additional window.onload functions to show the image name on page load:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("home-image-name").innerHTML = src;
}
});
}
So, from what I said + #j08691 comment, the correct sintax would be:
document.getElementById("home-image-name").innerHTML = src;
As the getElementById method takes a string of the id, with no need of #. And output was just a string, so you could either change output = src which is kind of redundant, or just put src.
Jquery way:
$("#home-image-name").html(src)
If you want to also do it on page load before click:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
}
Using jQuery, a simple:
$('#home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
should work.
jsFiddle example
Also if you wanted to use this code with several images, you could use the following (which uses a common class):
$('.home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
jsFiddle example
remove the # from
document.getElementById("#home-image-name").innerHTML = output;
Related
This question already has answers here:
How do I check if file exists in jQuery or pure JavaScript?
(19 answers)
Closed 3 years ago.
We are currently developing a web interface (only for viewing) for one of our applications, which is C++ based. The web application uses Bootstrap. I am a JavaScript and JQuery beginner.
At the top of the web page I need to display a thumbnail if it's available, otherwise a default picture.
I have the link to the thumbnail, even if it's not pointing at any resources (the picture can be deleted for different reasons that are irrelevant here, and this is not an error). The link to the thumbnail has the following format /resources/id={some_id}
Using jquery, I do the following :
<html>
<body>
<img id="thumbnail" />
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
/* thumbnailSrc will always contain something valid,
but that can point to some not existing picture */
let thumbnailSrc = jobDescription.thumbnailSrc;
$('#thumbnail').attr("src", thumbnailSrc);
});
</script>
</body>
</html>
If the link is valid, everything is fine; otherwise, it displays a broken picture. I would like to test if thumbnailSrc is a valid link (not returning a 404 error) to be able to do something like:
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
let thumbnailSrc = jobDescription.thumbnailSrc;
if (/* thumbnailSrc link is working */)
$('#thumbnail').attr("src", thumbnailSrc);
else
$('#thumbnail').attr("src", "/resources/default_picture.png");
});
</script>
How can I test in Javascript (or JQuery) if a link is valid?
Use a callback function like below
<img src="image.gif" onerror="myFunction()">
<script>
function myFunction() {
alert('The image could not be loaded.');
}
</script>
You can assign to your image an onerror event, and inside it you can assign to src the fallback source, e.g. in jQuery it would be like this:
$(function() {
$('#thumbnail').on('error', function() {
let fallback_img_src = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
$(this).attr('src', fallback_img_src);
});
let wrong_img_src = 'wrong_img_src.jpg';
$('#thumbnail').attr('src', wrong_img_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="thumbnail" />
The following loads the image and if 404, loads the default:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
el.addEventListener("load", function(ev) {
document.body.appendChild(el);
});
el.addEventListener("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
In jQuery:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
$(el).on("load", function(ev) {
document.body.appendChild(el);
});
$(el).on("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have tried searching and nothing I am finding works. the site this is for does NOT work with php, I know how to with php, but I need any other way.
I just want a simple IF THEN statement to say if website is www.a.com then "this style sheet" "this page title" "this logo", etc. I will use the if function many times through the page. if site is a.com, this image, this text, etc. if is b.com, then everything is different.
I also want it to only recognize the domain itself, so if on a.com/thispage.html , then it would still load with the proper data.
reason being, I have two site pointed to the same folder, which is a store, same product, etc. however we market the product as 'a' and as 'b'. so I just want to see what site the user is on and pull the proper info regarding that site.
this is what I have come up with, but does not generate the required html.
<script>
window.onload = function ()
var element = document.getElementbyId('idElement');
if (location.href == "a.com")
{
<link href="/landing.css" rel="stylesheet" type="text/css" />
}
if (location.href == "b.com")
{
<link href="/landing2.css" rel="stylesheet" type="text/css" />
}
</script>
<script>
if (location.href == "a.com")
{
<title>AAAAAAAAAAAAA</title>
}
if (location.href == "b.com")
{
<title>BBBBBBBBBBBBB</title>
}
</script>
<script>
if (location.href == "a.com")
{
<img src="a.png">
}
if (location.href == "b.com")
{
<img src="b.png">
}
</script>
etc, etc, etc
You can achieve this by having an array that holds an object with metadata about each site. When the script runs you create a new link element for the css and add it to the head and set the document title.
Do notice that DOM content can only be found (and then changed) after it is loaded, hence the use of an eventlistener for DOMContentLoaded.
This leads to the following implementation in the html script tag:
<html>
<head>
<title>
NotSet
</title>
<script>
(function () {
"use strict";
// have an array sites with data
var sites = [{
url: 'a.com', // if location.href contains this
title: 'AAAAAAAAAAAAA', // use this title
css: '/landing.css', // use this css file
images: [{id: 'idOfImage', src: 'a.png'}] // replace those ids with src
}, {
url: 'b.com',
title: 'BBBBBBBBBBBBB',
css: '/landing2.css',
images: [{id: 'idOfImage', src: 'b.png'}]
}
],
site, siteIndex, NOT_FOUND = -1;
//create a link for the css and add it
function addLink(css) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = css;
document.head.appendChild(link);
}
// find the img tags by id and set the src
function setImages(images) {
var image, imgIndex, img;
for (imgIndex = 0; imgIndex < images.length; imgIndex = imgIndex + 1) {
image = images[imgIndex];
img = document.getElementById(image.id);
if (img !== null) {
img.src = image.src;
}
}
}
// iterate over our sites array
// at the end site will have an object or is null (if no match found)
for (siteIndex = 0; siteIndex < sites.length; siteIndex = siteIndex + 1) {
site = sites[siteIndex];
// is url found in location.href
if (window.location.href.indexOf(site.url) > NOT_FOUND) {
break;
}
site = null;
}
// if we have a site do what is needed
if (site !== null) {
addLink(site.css);
// IE9 or up...
document.addEventListener("DOMContentLoaded",
function () {setImages(site.images); }
);
// set the title
document.title = site.title;
}
}());
</script>
</head>
<body>
Does this work?
<img id="idOfImage" src="none.png" />
</body>
<html>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I want to change an image onClick and change it back oClick.
This is my current code, but for some reason it doesn't work. I can't find out what's wrong with it.
var newsrc = "suspects.png";
var newsrc = "questionmark.png";
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
}; else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
};
};
I´m pretty sure it´s good like this... Why doesn´t it work?
Toggle a image only checking the source
function toggle(){
var img=document.getElementById('img');
img.src=img.src=='url1'?'url2':'url1';// needs to be the full url.
}
Regarding you code:
you define newsrc 2 times and so the first one is lost.newsrc is always "questionmark.png"
}; else{
should be
}else{
and
if you have suspects set then you want questionmark if clicked, and not suspects.so invert the if content.
should be
if suspects then questionmark else suspects
you have
if suspects then suspect else questionmark.
DEMO
http://jsfiddle.net/SLkHu/
Remove extra semicolons ; in your code
It should be
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
} else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
}
}
I have been trying to use javascript to change the image on a webpage I have made. so far my code dosn't do anything at all when I click on the original image. this is my first experiment with JS in a html doc so i could be something simple about how i have to use it.
<h1>heading name</h1>
<div>
<img alt="alt text"title='hover over text'id='chango'src="images/rsz_josh.jpg"onclick="changeImage()"/>
<script language="javascript">
var changeImage = function(){
img1="images/rsz_josh.jpg";
img2="images/rsz_josh2.jpg";
img3="images/rsz_josh3.jpg";
switch(document.getElementById('chango').src){
case img1:
document.getElementById("chango").src=img2;
break;
case img2:
document.getElementById("chango").src=img3;
break;
default:
document.getElementById("chango").src=img1;
break;
};
};
</script>
</div>
The reason is that document.getElementById('chango').src returns an absolute URL to the image, not a relative one. Thus none of your case statements match.
An idea for fixing that is to split the URL at the slashes and just compare the filename without any path.
EDIT: A slightly easier way would be to use JavaScript's indexOf to see if the URL contains the string. This assumes none of the image names are substrings of other image names.
var changeImage = function(){
img1 = "rsz_josh.jpg";
img2 = "rsz_josh2.jpg";
img3 = "rsz_josh3.jpg";
console.log(document.getElementById('chango').src);
imgUrl = document.getElementById('chango').src
if (imgUrl.indexOf(img1) != -1) {
document.getElementById("chango").src = 'images/' + img2;
}
else if (imgUrl.indexOf(img2) != -1) {
document.getElementById("chango").src = 'images/' + img3;
}
else {
document.getElementById("chango").src = 'images/' + img1;
}
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);