changing <img> tag src with javascript - javascript

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

Related

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>

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

src image changer after click with JavaScript

I have this image in my html page:
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
and in my javascript code i have this:
function act_deact(image) {
image.src = (image.src=="/images/activate.png" ) ? "/images/deactivate.png" : "/images/activate.png";
}
and when i click on the image that initially deactivated it activate but in the second click it doesn't desactivate !
is there any probleme with my code ?
from JS amateur :)
This is because when you set it to(or it changes to) /images/activate.png on first click, the src attribute is no longer just /images/activate.png but it gets prefixed with the server-address.
You can check it here: http://jsfiddle.net/hGcqq/
Or on your own server, use a console.log or an alert if you prefer.
#hjpotter92 already explained the reason it doesn't work.
One way to make it work is to check if src ends with /images/activate.png:
var activateURL = '/images/activate.png';
if (img.src.substring(img.src.length - activateURL.length) !== activateURL) {
image.src = '/images/activate.png';
} else {
image.src = '/images/deactivate.png';
}
The image.src contains the canonical path, even if initialised with a relative path. You can either use the full path in the condition like
function act_deact(image) {
image.src = (image.src=="FULL-PATH-OF-IMAGE" ) ? "/images/deactivate.png" : "images/activate.png";
}
(to get the full path one may use alert(image.src);)
or, if all your images have unique names
function act_deact(image) {
image.src = image.src.match(/activate.png$/) ? "/images/deactivate.png" : "images/activate.png";
}
The first thing is brackets which should be like this:
image.src = (image.src=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png")
Also try image.getAttribute("src") and image.setAttribute("src") instead of image.src.
Please try this code:
function act_deact(image) {
image.setAttribute("src", (image.getAttribute("src")=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png"))
}
Edit: other answers tell you about the issue of absolute and relative urls, so getAttribute will fix that issue. I do not recommend to use RegExp or substrings here.
To make it work with relative url you can simply save current url like this:
var newsrc = "/images/deactivate.png";
function act_deact(image) {
if ( newsrc == "/images/deactivate.png" ) {
image.src = "/images/activate.png";
newsrc = "/images/activate.png";
}
else {
image.src = "/images/deactivate.png";
newsrc = "/images/deactivate.png";
}
}
and then call it
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
I found the solution myself :p and i have tried #fardjad proposition that is looking for string in the url and make conditions
i share the solution :)
function act_deact(image) {
if(image.src.indexOf('deactivate') != -1)
image.src="/images/activate.png";
else
image.src="/images/deactivate.png";
}
#hjpotter92: the solution with check condition on image.alt works to:
html:
<img alt="deactivate" src="/images/deactivate.png" onClick="act_deact(this);" />
the Js function :
function act_deact(image) {
if (image.alt=="activate") {
image.src = "/images/deactivate.png";
image.alt = "deactivate" }
else {
image.src = "/images/activate.png";
image.alt = "activate"
}
}
thanks for your responses :)

Dynamically replace img src attribute with jQuery

I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.gif etc.
EDIT: The images are retrieved from an XML to a random order, without class to each .
This is what I tried:
if ( $("img").attr('src', 'http://example.com/smith.gif') ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( $("img").attr('src', 'http://example.com/williams.gif') ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
Note that my HTML has many images. For example
<img src="http://example.com/smith.gif">
<img src="http://example.com/williams.gif">
<img src="http://example.com/chris.gif">
etc.
So, how can I replace the images: IF img src="http://example.com/smith.gif" then show "http://example.com/williams.gif". etc...
Thanks alot
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.
http://api.jquery.com/attr/
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
In my case, I replaced the src taq using:
$('#gmap_canvas').attr('src', newSrc);

Categories