Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the background image of div using javascript?

this is my code

<div style="text-align:center;">   <div class="ghor" id="a" onclick="chek_mark()"></div>   function call </div> <script type="text/javascript">   function chek_mark(){    var el= document.getElementById("a").style.background-image;    if (el.url("Black-Wallpaper.jpg"))      {      el.url = "cross1.png";     }     else if(el.url("cross1.png"))     {       alert("<h1>This is working too.</h1>");      }    } </script> 

here I want to change the background image using if else condition

this is the style-sheet .ghor //this is the div class {     background-image: url('Black-Wallpaper.jpg');     background-size: cover;     border-radius: 5px;     height: 100px;     width: 100px;     box-shadow: 2px 5px 7px 7px white;     /*background-color: black;*/     display:inline-block;  } 

i want change the background image of the 'div' which class is 'ghor'

like image 290
shajib0o Avatar asked Feb 01 '14 10:02

shajib0o


People also ask

Can you give a div a background image?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.

Can JavaScript change the background image of body?

When you want to change a webpage background image using JavaScript, you can do so by setting the background image of the document object model (DOM) property. The property you need to manipulate for changing the background image of the whole page is document. body.


2 Answers

Try this:

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

Hope it helps!

like image 184
immayankmodi Avatar answered Oct 01 '22 21:10

immayankmodi


try this one!

var el = document.getElementById("a").style.backgroundImage; if(el == "url(Black-Wallpaper.jpg)") { // full value is provided    el.style.backgroundImage = "url(/link/to_new_file.png)"; // change it } 
like image 41
Afzaal Ahmad Zeeshan Avatar answered Oct 01 '22 22:10

Afzaal Ahmad Zeeshan