I want to ask a question about javascript image src - javascript

<img src="../1.jpg" alt="" id="change-image">
<button id= "press-to-change">Press</button>
let count = 0;
let arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]
document.getElementById("press-to-change").addEventListener("click", function(){
count++;
document.getElementById("change-image").src = "../" + arr[count]
So we have an HTML with an image and a button and in JS we have an array with images and we want to change the src of the image when we press the button(this is only a part of the code)
The above code works fine but i have a question why with:
document.getElementById("change-image").src = "../" + arr[count] code works fine but with document.getElementById("change-image").src = `url('../${arrImage[count]}')` code doesn't work.
For example this next code from another project works perfectly imageContainer.style.backgroundImage = `url('../${arrImage[count]}')`

background-image is a for style of an element and uses css format.
src is for the actual source of the image element and requires a valid path only

With images, you use or assign to the src property only for <img> elements.
If you want to set the background image of an arbitrary (but non-<img>) element, you need to use different syntax: you have to assign to the style.backgroundImage property, and you have to surround the URL you're setting with url(...)
The rendered HTML markup looks like this:
<img src="foobar.png">
<div style="background-image: url('foobar.png');"></div>
They're not interchangeable. With the background-image property, you need to always use url(...). With the src attribute, you need to never use url(...).

The text: url(image.jpg) is syntax only used in CSS.
That’s why it works for backgroundImage but not src
An image will always need src="path/to/image.jpg" without url() surrounding it.

Related

change some text in src of image tag using jquery [duplicate]

This question already has answers here:
Changing the image source using jQuery
(17 answers)
Closed 4 years ago.
I want to change one letter in the src of the image tag using js or jQuery.
<img src="/media/image_i/ball.png">
<img src="/media/image_i/bat.png">
I want to change that letter i in the src to a number.
Eg.it should look like this -
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
EDIT- When i used the solutions everything was working, but it was changing the "src" of all image tags to same as first image, so the second image which is "bat.png" is getting changed to "ball.png", so same image is displaying two times.
Thank you!
You can simply get the src attribute of the images, loop it over and replace the _i with _4 using JQuery. To check the below snippet works, you need to use inspect element of the browser and check the src attribute.
$(document).ready(function(){
$('img').each(function(){
var src = $(this).attr('src');;
$(this).attr('src', src.replace('_i','_4'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
You can do this job using regex.
$(document).ready(function(){
var src = $('img').attr('src');
var newsrc = src.replace(/_./g, '_4');
$('img').attr('src', newsrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_i/ball.png">
You can develop it further.
For more : https://stackoverflow.com/a/2912904/5792209
First, you'll need to identify the particular img element you need to modify. This can be done in a variety of ways, like giving the img in question an id or a class that is unique. If the image is the only one using the src you've specified in your question, you can use that (and that's what I'm doing in the code that follows).
After getting the proper reference to the element, use the .attr() method to get/set the current src value and the standard String.replace method to swap the values:
var current = $("img[src='/media/image_i/ball.png']");
current.attr("src", current.attr("src").replace("_i", "_4"));
If this is all you need to do, JQuery is overkill. Standard JavaScript is just as simple:
var el= document.querySelector("img[src='/media/image_i/ball.png']");
el.src = el.src.replace("_i", "_4");

How to reference an image within quotation marks in a script

I am trying to reference an image instead of using text within the script tag in a html page. I am attempting to use an image for a button instead of text. When the button is pressed it changes to the text 'Paused' as shown below.
pauseButton.innerHTML = "Paused";
When it is pressed again it displays the words 'Pause'.
pauseButton.innerHTML = "Pause";
Instead I would like it to display an image I created. This code shows a section where I tried to reference the image.
pauseButton.innerHTML = "url(Images/pausebackground.png)";
Instead of displaying the image it displays 'url(Images/pausebackground.png)' in the form of text.
How can I reference the image within the quotation marks?
You need to put HTML code into innerHTML (as the name suggests). Use an <img> tag:
pauseButton.innerHTML = '<img src="Images/pausebackground.png">';
An image in HTML uses the <img> tag, which has a src attribute pointing to the image URL, as so:
<img src="Images/pausebackground.png">
To insert the image into the HTML, you could use innerHTML, but it is best to add an actual HTML element:
var image = document.createElement('img'); // Create the HTML element
image.setAttribute('src', 'Images/pausebackground.png'); // Set the image src
pauseButton.appendChild(image); // Place it inside the button
To set a different image, all you need to do is change the src attribute on the image tag.
The innerHTML property will change the html inside the element:
<div>
Here is the inner html.
</div>
If you wish to add a image to the inner html, you could use a normal image tag, but remember, just setting the innerHTML will remove anything that is inside of it already.
pauseButton.innerHTML = '<img src="Images/pausebackground.png" />'
If you wish to use the image as a background of the button (which I guess you would rather do) you could either just set the image as the elements style.backgroubndImage property or rather, create a css class and add it to the button when you need (through js).
// Alt 1, changing the style of the element:
pauseButton.style.backgroundImage = "url(Images/pausebackground.png)";
// Alt 2, creating a css class and adding it to the element when needed:
// CSS.
.my-special-button-class {
background-image: url(Images/pausebackground.png)
}
// JS.
pauseButton.classList.add("my-special-button-class");

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML looks like
<div id = "image">
Hover over an image below to display here.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()">
That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
var div_element = document.getElementById('image').innerHTML;
var picurl = "url(previewPic.getAttribute('src'))"
div_element.style.backgroundImage = "url(picurl)";
}
And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
There are multiple issues with your code.
Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.
Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
var div_element = document.getElementById('image');
var picurl = "url(" + previewPic.getAttribute('src') +")"
div_element.style.backgroundImage = picurl;
}
This should work.
If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){
$('div').css(''background-image:'url("image_link")');
});

find & replace part of file path for 'src' attribute

Assuming I have a theme switcher, and there're multiple images/icons
<img src="images/icons/icon-1.png">
<img src="images/icons/icon-2.png">
<img src="images/icons/icon-3.png">
<img src="images/icons/icon-4.png">
And also I have another set of these icons with a different color/path
<img src="images/icons/blue/icon-1.png">
<img src="images/icons/blue/icon-2.png">
<img src="images/icons/blue/icon-3.png">
<img src="images/icons/blue/icon-4.png">
the below jQuery code working perfectly when I click to change theme color for 'once'
$('img').attr('src', $('img').attr('src').replace('images/icons', 'images/icons/blue'));
If I clicked again to choose another color say 'red', the path become like this
<img src="images/icons/red/blue/icon-1.png">
while it's supposed to be like this
<img src="images/icons/red/icon-1.png">
how I can make 'replace method' to find & overwrite old path WITHOUT change file name 'icon-1.png' for example, as it's a dynamic icons.
Thanks in advance.
Is the name always the same? in that case you can use the following code
$('img').attr('src', function(i, src){
return 'images/icons/blue/' + src.split("/").pop()
});
You need to loop and replace the src of each element.
$('img').attr('src', function(i, src){
return src.replace('images/icons', 'images/icons/blue')
});
When you use the getter version of .attr() it will return the attribute value of the first element in the matched element set, so the same value will get set for all elements.
Just get the filename from the source first, then rewrite the whole source. Assuming that you send as "theme" to changeTheme function, something from the following values: "images/icons", "images/icons/blue", "images/icons/red", etc. this will do the trick.
function changeTheme(theme) {
var img=$(img);
var filename=img.attr('src').split('/');
filename=filename[filename.length-1];
img.attr('src',theme+"/"+filename);
}
Or if you don't minde storing the file name as a data attribute to the image, you can change the second and third lines of the functions, with something along the lines of:
var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute

Change img src on click in list

I'm trying to make an image which changes based on clicking on images in a list.
The only trouble is, the images in the list have their url embedded in a style as a background-image.
How would I call the url of the img src to the new image?
<ul id="swatchList_att1"><li class="Name AttributeSwatch In_stock colourSwatch" id="attributeSwatch_1" data-attname="att1" data-attvalue="Deep Blue (001)" data-atrsku="0012345" style="background-image: url(https://color.adobe.com/api/v2/themes/2022184.png);">
EDIT
Wow, great response time.
and
Wow, I phrased this incredibly poorly yesterday. Apologies.
The list "swatchList_att1" is a group of color swatches which are shrunk to 50% of the jpeg size.
All I'm trying to do is create a sort of "Preview" image which sits in a different div and will show a selected color swatch at an inflated size (110%). On page load, it would be the first color in the list. When a click occurs on a color in the group of color swatches, the "Preview" image would change to what color was clicked.
I can't make changes to how these list items work (i.e. change it to "data-background") because the functionality behind the scenes would break. Annoyingly, I can't do much about that. These list objects need to have their image defined in "style", for whatever reason (I don't know). I can, however, add an onclick function to the list (if I had something that could apply it to all items in the list, which all have very long and different names).
Thus I need to extrapolate the url from the "style" onclick and have "Preview" img src change to that url.
In response to BearSkyView:
Since it's a seperate image, this isn't exactly what I meant. Also, I'd need something which applied an onclick to everything in the list.
In response to somethinghere:
That is more closely along the lines of what I'd like to accomplish, but as I can't change the way these list objects are made, this sadly won't work for me.
http://api.jquery.com/css/
$('#attributeSwatch_1').css("background-image", new src here);
EDIT: Are you looking for something like this? http://jsfiddle.net/rsqtL805/
Since you are using data-attributes anyway, why don't you put it into one? Say data-background="URL".
<img src="" id="myImageElement" alt="large image" />
<img src="path/to/image.jpg" data-background="path/to/image.jpg" onclick="setImg(this); return false;" alt="thumbnail" />
function setImg(obj){
var img = obj.getAttribute('data-background');
document.getElementById("myImageElement").attribute("src", img);
}
Otherwise you can read the background image property and split it in javascript to retrieve the URL and do with it as you like:
var img = this.style.backgroundImage;
img = img.split("rl(")[1].split(")")[0];
The above will take the following string:
url(path/to/image.jpg);
And split it first into:
[0] => u
[1] => path/to/image.jpg)
And then we split the element at place 1 at the ) and select the remainder at index 0.
[0] => path/to/image.jpg
[1] =>
With that you could do
document.getElementById("myImageElement").attribute("src", img);
to set the src of the image element to the just retrieved source.

Categories

Resources