How to Change the Background Image of Div Using JavaScript

how to change the background image of div using javascript?

Try this:

document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here

Hope it helps!

Set background-image of div in JavaScript

Looks good so far. The new div has to be appended to the DOM.

$.getJSON("https://www.khanacademy.org/api/internal/user/profile?kaid=kaid_783146703471696540623752&callback=?", function() {    console.log("success");
var bg = document.createElement("div"); document.body.appendChild(bg); bg.style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg/1280px-Basilica_of_Saint_Achilles%2C_Florina%2C_Greece.jpg')";
bg.style.height = "100px";
}) .done(function() { console.log("second success"); }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); });
div {  border: 1px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

Change Background Image in Div using JS

Please use this fiddle

imgArea = document.getElementById("picArea");
var images = [ "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];var currentImage = 0;
function changeImage() { currentImage++; if (currentImage > images.length - 1) { currentImage = 0; } imgArea.style.backgroundImage = "url(' "+ images[currentImage] + "')";
}setInterval(function(){ changeImage();}, 3000);
#picArea{  width:500px;  height:500px;}
<div id="picArea" ></div>

Changing the background image when clicking on the div?

Instead of using onclick, maybe try using something Tomm did. I probably encourage you to create a class for all of these id elements. Since you had a shared background image for the original background before the function is clicked, I added background-position. Here is what I did for the script by making a function that I put in the onload of the body (first portion is for backgrounds when clicked, second portion is for original background and will only show for those that are not clicked):

function onloadPage() {
// first portion
$('#sw').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
$('#sl').click(function() {
$(this).css("background-position", "0 0");
document.getElementById("info").innerHTML = 'INFO HERE';
});
...

// second portion
$('.classname').on('click', function(e) {
if(!$(e.target).closest('#sw').length) { $('#sw').css("background-position", '0 0'); }
if(!$(e.target).closest('#sl').length) { $('#sl').css("background-position", '0 0'); }
...
}

And then the HTML:

<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><div class="classname" id="sw" style="background-position:0 0;"></div></td>
<td><div class="classname" id="sl"></div></td>
<td id="classinfo" rowspan="3" style="width:325px;"></td>
</tr>
</table>

Obviously you will have to adjust your background-positions to the way you need it to look.

Change css background-Image using javascript

Problem :

  1. You don't need to create img tag to apply background-image in
    CSS Style
  2. You are applying only image path

Solution : You need to apply image path between URL() just like
normal CSS background image applies

Check below code :

var images = ['https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random'];var index = 0;
function buildImage() { document.getElementById('content').style.backgroundImage = 'url('+images[index]+')';}
function changeImage() { index++; if (index >= images.length) index = 0; document.getElementById('content').style.backgroundImage = 'url(' + images[index] + ')';}
.contents {    width: 200px;    height: 200px;    border: 2px solid #FF0000;}
<div class="contents" id="content"></div><button onclick="changeImage()">NextImage</button>

changing background image of div using javascript

You need to pass the image source with url like divblock.style.backgroundImage = "url('url of the source')";

function upDate(previewPic) {  var divblock = document.getElementById('image');  var img = previewPic.src;  divblock.classList.add('hoverDiv');  divblock.style.backgroundImage = 'url(' + img + ')';  divblock.innerHTML = previewPic.alt;}
function unDo() {}
.hoverDiv {  width: 500px;  height: 500px;  margin-bottom: 20px;  color:red;}
<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()"><img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()"><img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()">

Changing div background image based on website URL using JavaScript

change:

<script type="text/javascript">
if(window.location.href === "/customers/topic/multi-channel-retail") {
document.getElementById("multi-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/1-active.png')";
document.getElementById("multi-text").style.color = "#005aa0";
}
else if(window.location.href === "customers/topic/manufacturing") {
document.getElementById("manufacturing-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/2-active.png')";
document.getElementById("manufacturing-text").style.color = "#b51c22";
}
else if(window.location.href === "/customers/topic/wholesale-distribution") {
document.getElementById("wholesale-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/3-active.png')";
document.getElementById("wholesale-text").style.color = "#009ae4";
}
</script>

with this:

<script type="text/javascript">
if(window.location.pathname === "/customers/topic/multi-channel-retail") {
document.getElementById("multi-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/1-active.png')";
document.getElementById("multi-text").style.color = "#005aa0";
}
else if(window.location.pathname === "/customers/topic/manufacturing") {
document.getElementById("manufacturing-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/2-active.png')";
document.getElementById("manufacturing-text").style.color = "#b51c22";
}
else if(window.location.pathname === "/customers/topic/wholesale-distribution") {
document.getElementById("wholesale-active").style.backgroundImage = "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/3-active.png')";
document.getElementById("wholesale-text").style.color = "#009ae4";
}
</script>

this would do the trick, however I would suggest you, to modify your HTML and add a class on this line like "MANUFACTURING-CSS-CLASS-ACTIVE"

<div id="manufacturing-active" class="span4 MANUFACTURING-CSS-CLASS-ACTIVE" onclick="window.location.href='/customers/topic/manufacturing';" style="background: url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/2-inactive.png?t=1528443115464') 50% 50% no-repeat;">
<div class="message"><span id="manufacturing-text" class="manufacturing">Manufacturing</span></div>
</div>

and in your .css add

.MANUFACTURING-CSS-CLASS-ACTIVE { //change the name of the class
backgroundImage: "url('https://www.sanderson.com/hubfs/Customers%20-%20Blog%20Page/2-active.png')";
color:"#009ae4";
}

you can do this for all 3 menus

How to change div background-image with linear-gradient from Javascript

Please try this.

function abc1() {
var pos = document.getElementById("test");
pos.style.background="linear-gradient(to right, #85e085 90%, #ff9999 10%)";
}
<div 
id="test"
style="background: linear-gradient(to right,
#85e085 50%,
#ff9999 50%); width:200px;"
>
dsfhdh2346346
</div>
<input type="button" value="CHANGE" onClick="abc1()" />

Changing background image using Javascript

I think the problem is in how you are trying to change the background image. The first time you set it, you are setting it in the stylesheet. You are using a CSS property there.

Later, you try to change it using the .style property of the element. These aren't the same thing. From this page:

The style property is not useful for completely learning about the
styles applied on the element, since it represents only the CSS
declarations set in the element's inline style attribute, not those
that come from style rules elsewhere, such as style rules in the
section, or external style sheets.

To clarify, try this in your console on this very page: document.querySelectorAll('input[type="submit"]')[3].style

This grabs the blue button at the bottom of the page that says "Post Your Answer". It's pretty clearly got a blue background that is set in the CSS. But that CSSDeclaration object in your console has only empty values. That's because it only reflects the inline styles, not the styles you applied with CSS.

Fun, right? With that knowledge, I think you can choose one way or the other to make your slideshow happen the way you expect. It's probably easiest to not use background image at all, though. I think it's conventional to have an img tag there and use javascript to set the src attribute.



Related Topics



Leave a reply



Submit