Q:

How to Set CSS background-image Property Using jQuery

0

How to Set CSS background-image Property Using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery CSS() Method

To set the CSS background-image property of an element using the jQuery CSS() method, you need to specify the complete property value using the url() functional notation.

For example, if you've an image URL stored in a JavaScript variable then in CSS() method you need to set the value something like this to make it work:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Setting background-image CSS Property</title>
<style>
    .box{
        width: 500px;
        height: 300px;
        border: 5px solid #333;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Set background image of a div on click of the button
    $("button").click(function(){
        var imageUrl = "images/sky.jpg";
        $(".box").css("background-image", "url(" + imageUrl + ")");
    });    
});
</script>
</head>
<body>
    <div class="box"></div>
    <p><button type="button">Set Background Image</button></p>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Detect a Mobile Device in jQuery... >>
<< How to Find an Element Based on a Data-attribute V...