Change the background image of an element - javascript

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")');
});

Related

I want to ask a question about javascript image src

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

Selecting an image element by using the source attribute to find it

I'm working on a script for a website, and I need to change the icon of one of its images. The problem is the image on the site only has a tag like this:
<img src="/pic1.png" alt="clear" >
I have tried selecting the image by using:
document.querySelector("img[src='pic1.png']");
What I have tried looks like this:
var y = document.querySelector("img[src='/pic1.png]'");
y.innerHTML = "<img src='pic2.png' alt='clear'>";
I also tried
var y = document.querySelector("img[src='/pic1.png]'");
y.src = "/pic2.png";
Is there anyway I can find the image using the src attribute, assign it to a variable, then replace the src?
Your help is appreciated :)
Your last example should work
var y = document.querySelector("img[src='/pic1.png']");
y.src = "/pic2.png";
y.load()
How about you set an Id on that element, then select it using document.getElementById(), then you can proceed to access the src property, which can help you change its value.

Getting image source from image element using $(this).find("");

I'm currently stuck trying to get the image source (eg: ./imgs/image.jpg) from an image element.
I've managed to get it working, partially, by using the following:
var image = document.getElementById("home-our-doughnuts-box-image").getAttribute("src");
But I need to use $(this).find("#MY_IMAGE_ELEMENT_ID_HERE").getAttribute("src"); so it references the correct box and image (I have multiple containers with elements in them that share the same ID, same with the box).
So how can I access the images src attribute to return the unresolved path using $(this).find(), as it's not working ?
Thank you.
EDIT
I am using this because I have assigned a click function to each of the boxes. So need to use $(this) to reference that particular box.
Full Code:
box.onclick = function() {
var image = $(this).find("#home-our-doughnuts-box-image").getAttribute("src");
alert(image);
doughnutExpandedName.text($(this).find("#home-our-doughnuts-box-name").text());
doughnutExpandedDesc.text($(this).find("#home-our-doughnuts-box-desc").text());
};
Try this:
var src = $(this).find("#MY_IMAGE_ELEMENT_ID_HERE").attr("src");

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

Java Script Mousovers

I am implementing a mouseover, which changes the background of a div onMouseDown, and onMouseUp, I am also trying to preload the images.
This is what I have so far;
if(document.images) {
buttonDown = new Image();
buttonDown.src = "buttonDown.png";
}
function down(affect) {
affect.style.backgroundColor="#333333";
affect.style.color="#ffffff";
affect.style.background = buttonDown;
return true;
}
the div uses onMouseDown="down(this);"
This doesn't work. The only part that doesn't work is -- affect.style.background = buttonDown;
I left out the script tags, but they are all there and work as they should.
My question is how do I assign the background property to a preloaded image verses just using a string to assign the image by name.
First, I think you are accessing the wrong style attribute; If you are going to use backgroundColor, may as well go with the more specific backgroundImage.
Second, it requires a string, not an Image Object.
Try this:
affect.style.backgroundImage='url(' + buttonDown.src + ')';
All that said, I would look into image Sprites and HTML classes (CSS) =)
I did some more research and this is what I found. You can preload the images by using a div which is set to style="display:none" and within that div include the images.
As long as the next time you refer to the image, you use the same path it will be preloaded.

Categories

Resources