
579 views
Move an image on button clicks in HTML using CSS and JavaScript
To move an image on button clicks in HTML using CSS and JavaScript, you can follow these steps:
- Create an HTML file and add the necessary HTML markup. Include an image element and a button element that will trigger the image movement.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Move Image on Button Click</title>
<style>
#image {
position: relative;
left: 0;
top: 0;
}
</style>
</head>
<body>
<img id="image" src="path/to/image.jpg" alt="Image">
<button onclick="moveImage()">Move Image</button>
<script src="script.js"></script>
</body>
</html>
- In the
<style>
section of the HTML file, define the initial position of the image using CSS. Theposition
property is set torelative
, and theleft
andtop
properties are initially set to0
. - Create a JavaScript file called
script.js
and add the following code to handle the image movement:
JavaScript
function moveImage() {
var image = document.getElementById('image');
var currentPosition = parseInt(image.style.left) || 0;
var newPosition = currentPosition + 10; // Adjust the value as desired
image.style.left = newPosition + 'px';
}
- In the JavaScript code, the
moveImage()
function is triggered when the button is clicked. It retrieves the image element usinggetElementById()
. The current position of the image is obtained usingparseInt(image.style.left)
and stored in thecurrentPosition
variable. ThenewPosition
variable is calculated by adding a desired value to the current position. Adjust the value as needed to control the amount of movement. - Finally, the
left
style property of the image is updated with the new position, and the image will be visually moved on each button click.
Save the files and open the HTML file in a web browser. Clicking the “Move Image” button will trigger the movement of the image to the right. You can adjust the code and CSS properties as needed to achieve different movement directions or effects.