Search code examples
javascriptjquerycss

Why is jquery.css() function to set an element's background-image url is not working?


I've been trying to apply background image to a div via the jquery.css() function, such as:

$('#div').css('backgrounds-image','./assets/imgs/flag.png');

Expected: to see the image being displayed on the div., but it didn't work.

HTML:

<div class="img-viewer"></div>

CSS:

div.img-viewer {
  min-width: 200px;
  min-height: 200px;
  background-image: none;
  background-repeat: no-repeat;
}

JQuery:

$('div.img-viewer').css('background-image','./assets/imgs/flag.png');

Solution

  • As per the documentation of: background-image

    You are missing url() in your code. [syntax usage issue]

    Here is a working example:

    $('div.img-viewer').css('background-image', 'https://www.shutterstock.com/image-photo/half-alive-dead-tree-260nw-1718611903.jpg');
    $('div.img-viewer-second').css('background-image', 'url(https://www.shutterstock.com/image-photo/half-alive-dead-tree-260nw-1718611903.jpg)');
    div.img-viewer,
    div.img-viewer-second {
      min-width: 200px;
      min-height: 200px;
      background-image: none;
      background-repeat: no-repeat;
    }
    
    div.img-viewer p {
      color: red;
    }
    
    div.img-viewer-second p {
      color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    
    <div class="img-viewer">
      <p>First one without background image due to CSS syntax violation</p>
    </div>
    <br>
    <div class="img-viewer-second">
      <p>Second one with background image due to correct CSS syntax usage</p>
    </div>