Cover Image for Move an image on button clicks in HTML using CSS and JavaScript
257 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:

  1. 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>
  1. In the <style> section of the HTML file, define the initial position of the image using CSS. The position property is set to relative, and the left and top properties are initially set to 0.
  2. 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';
}
  1. In the JavaScript code, the moveImage() function is triggered when the button is clicked. It retrieves the image element using getElementById(). The current position of the image is obtained using parseInt(image.style.left) and stored in the currentPosition variable. The newPosition variable is calculated by adding a desired value to the current position. Adjust the value as needed to control the amount of movement.
  2. 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS