jQuery

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>

 

 

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

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *