JavaScript - Dynamically Change Background Image
Submitted by razormist on Wednesday, June 5, 2019 - 17:58.
In this tutorial we will create a Dynamically Change Background Image using JavaScript. This code will immediately change your background image when the user click a image. The code use onclick() function to initiate a method that change your image background source base on the click image. You can apply this script to your code to make your transaction faster, it is a user-friendly program feel free to modify it.
We will use JavaScript to add some new feature to the website interface by actually written into an HTML page. It is what gives your page a different interactive elements and animation that engage a user.
There you have it we successfully created a Dynamically Change Background Image using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting Started:
This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="col-md-6" style="border:1px solid #000; height:200px; padding-top:10%; padding-left:10%;" id="display">
- </div>
- <div class="col-md-12" style="border:1px solid #000; padding:10px;">
- <img src="images/image1.jpg" onclick="changeBackground(this)" height="150" width="150"/>
- <img src="images/image2.jpg" onclick="changeBackground(this)" height="150" width="150"/>
- <img src="images/image4.jpg" onclick="changeBackground(this)" height="150" width="150"/>
- <img src="images/image3.jpg" onclick="changeBackground(this)" height="150" width="150"/>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. This code will change image background when the button is clicked. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js directory- function changeBackground(image){
- document.getElementById('display').innerHTML="";
- document.getElementById('display').style.backgroundImage="url('"+image.src+"')";
- document.getElementById('display').style.backgroundSize="cover";
- }
Add new comment
- 381 views