How to Set CSS background-image Property Using jQuery
In this tutorial, we are going to see how to set CSS background-image property using jQuery. To change the background-image attribute of CSS in jQuery, use the method css() of jQuery, and then you can use the background-image attribute to add the background image.
HTML Code:
<!DOCTYPE html> <html> <head> <title>Set CSS background-image Property Using jQuerye</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> // Put the jQuery code Her. </script> <style type="text/css"> /* Put the CSS Style Here */ </style> </head> <body> <div class="image"></div> <p><button type="button" id="btn">Set the background image</button></p> </body> </html>
[st_adsense]
CSS Code:
.image { width: 600px; height: 400px; border: 4px dashed #000; }
jQuery Code:
$(document).ready(function() { $("#btn").click(function() { var url = "https://1.bp.blogspot.com/-rWHdFvjsDwA/XSJO7HQBxxI/AAAAAAAAFFA/_pIqqdkq4lMyZnxmjKrsxrVb9sepx-X6ACLcBGAs/s1600/sea.jpg"; $(".image").css("background-image", "url(" + url + ")"); }); });
Result |
---|