Move an image on button clicks in HTML using CSS and JavaScript

HTML, CSS, and JavaScript are commonly used together. Each language offers various features and characteristics, with CSS and JavaScript being particularly noteworthy. It is essential to consistently delve into these features to fully grasp them. Familiarizing ourselves with a wide range of options will greatly simplify the process of creating visually appealing and functional websites.

Here is an uncomplicated exercise to explore fundamental characteristics:

Objective: Shift an image by 10 pixels in various directions upon button clicks. For instance, pressing the right button should transition the image to the right by 10 pixels.

Directions:

  • Down
  • Right
  • Left
  • Top right diagonal
  • Top left diagonal
  • Bottom up diagonal
  • Bottom right diagonal

Steps:

  • Insert an image into the webpage
  • Create buttons for all the 8 directions
  • Write JavaScript functions to each button
  • Style the buttons using CSS
  • Test the working

So, let us follow the steps and start coding:

  • Create a new file and save it with .html extension.
  • We can either embed the CSS and JavaScript codes internally or you can create external files and link them to the html file.
  • We'll embed them using <style></style> and <script></script>

The basic skeleton:

Example

<!DOCTYPE html>
<html lang="">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>
<body>
   <h1>Picture Movement<h1>
</body>
</html>
<link rel="stylesheet" href="">
<style></style>
<script src=""></script>
<script></script>

Observe the colors:

  1. Now, we need to insert an image into the webpage using <img> tag:
  • See that the image is saved in the same location as the html file.
  • Example
    
    <img id="img" src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">
    
  • Otherwise, set src to the complete path of the location.
  • Example
    
    <img id="img" src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image">
    
  • Alternatively, you have the option to link an image hosted online. Keep in mind that each time you execute the file, an active internet connection is required to display the image.
  • Example
    
    <img id="img"src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image">
    
  1. Now, we need to build 8 buttons for the 8 directions:
  • On the buttons, we can write the name of the direction or we can simply display arrows.
  • We can use the decimal or hexadecimal codes to access the codes.
  • Here are the codes: Use &#code Eg: &#8592
  • We'll use a table to arrange the buttons to make it easy and equi-distance.
  • On clicking these buttons, we call a JavaScript function with argument as the direction of the button.
  • Using <center></center> we'll arrange the image as well as the button table in the center.

HTML Code:

Example

<body>
  <h1>Picture movement</h1>
    <center>
        <img id="img" src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image">
    <br>
    <br>
    <table>
    <tr>
        <td><button class = "b" onclick = fun("top-left")>?</button></td>
        <td><button class = "b" onclick = fun("up")>?</button></td>
        <td><button class = "b" onclick = fun("top-right")>?</button></td>
    </tr>
    <tr>
        <td><input type="button" class = "b" onclick = fun("left") value = "?"></td>
        <td></td>
        <td><input type="button" class = "b" onclick = fun("right") value="?"></td>
    </tr>
    <tr> 
        <td><input type="button" class = "b" onclick = fun("bottom-left") value = "?"</td>
        <td><input type="button" class = "b" onclick = fun("down") value = "?"></td>
        <td><input type="button" class = "b" onclick = fun("bottom-right") value = "?"</td>
    </tr>
    </table>
         </center>

On running:

Now is the moment to implement the actual behaviors for the buttons, or alternatively, we can first apply styling to the elements and then incorporate the functionalities.

Next, we will enhance the appearance of the buttons by applying basic CSS properties:

Example

<style>
        table{
            table-layout: fixed;
            border: 1px solid black;
            border-spacing: 10px;
        }
        
        .b{
            background-color: floralwhite;
            font-size: 20px;
            padding: 16px;
            border-radius: 8px;   
        }
        .b:hover{
            background-color: bisque;
            box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 	rgba(0,0,0,0.19);
        }        
    </style>

Output:

Properties used:

Property Explanation
table_layout: fixed The layout of all the cells in the table remains fixed (Width of the columns) irrespective of the length of content inside.
border-spacing: 10px Distance or space between the borders of cells. It applies only when border-collapse is set to separate. We can set both vertical and horizontal distances.
border One property for adding the width, style and color to the borders of an element.
border-radius To curve the edge of the element's corners. (To add rounded corners to an element). The greater the value, rounder the corner will be. We can give four values to four corners.
background-color The color to the background of an element. We can give the name of the color or use hexadecimal codes.
box-shadow To attach a shadow to an element. We can add multiple shadows to a single element by separating them by a comma.
padding To create space between the element and the border around it. Using padding-top, padding-right, padding-bottom and padding-left, we can give spaces on each side of the element.
.b:hover When the user hovers the curser on the button, we can alter the properties of the button like box shadow and background color to give a feeling of click.

JavaScript:

The functionality we use here is a CSS property: position . We can give five different values to the property:

  • static -> default
  • relative
  • fixed
  • absolute
  • sticky
Value Mechanism
static It is the default value when we insert an image into the document. It doesn't get affected by .left and .top modifications later in the code.
relative The position of the image is set relative to its normal position and we can alter the position using .left and .top properties later in the code. When moved, other elements won't take up the space cleared by the elements. The space stays emty until manual arrangements.
absolute The element is positioned relative to its nearest ancestor. If there are no ancestors nearby, the position will be set relative to the position of the body of the document. When moved, other elements occupy its space.
fixed The position is set relative to the position of viewport (visible part of the document). When moved, other elements take up the space cleared out by the element. Mostly used for navigation menus that stay in the same place even though user scrolls.
sticky Similar to relative. The difference is that the element remains fixed in its position until a certain point and then they become relative. This is used for navigation menus that need to be fixed until user scrolls up to a certain point only.

Code:

Example

<script type="text/javascript">
    var a=document.getElementById("img");
    a.style.position="relative";
    a.style.left="0px";
    a.style.top="0px";
    a.style.right="0px";
    a.style.down="0px";
    function fun(b)
    {
        if(b==="left")
        {
            
            a.style.left=(parseInt(a.style.left)-10)+"px";
        }
        if(b==="right")
        {
                a.style.left=(parseInt(a.style.left)+10)+"px";
        }
        if(b==="up")
        {
                a.style.top=(parseInt(a.style.top)-10)+"px";
        }
        if(b==="down")
        {
                a.style.top=(parseInt(a.style.top)+10)+"px";
        }
        if(b=="top-right")
            {
                a.style.left =(parseInt(a.style.left)+10)+"px";
                a.style.top=(parseInt(a.style.top)-10)+"px";
            }
        if(b=="top-left")
            {
                a.style.left =(parseInt(a.style.left)-10)+"px";
                a.style.top=(parseInt(a.style.top)-10)+"px";
            }
        if(b=="bottom-right")
            {
                a.style.left =(parseInt(a.style.left)+10)+"px";
                a.style.top=(parseInt(a.style.top)+10)+"px";
            }
        if(b=="bottom-left")
            {
                a.style.left =(parseInt(a.style.left)-10)+"px";
                a.style.top=(parseInt(a.style.top)+10)+"px";
            }
        
    }
</script>

Explanation:

When we utilize .style, we are gaining entry to the CSS properties of the element. Initially, we saved the image in a variable named 'a' and adjusted its positioning to relative. This adjustment enables us to manipulate the picture's placement using the .left and .top attributes, positioning it relative to its existing location. To make use of the positioning feature, it is imperative to set a value to the position property first, followed by modifying the element's position using the dot notation properties.

There are only left and top properties available, we'll have to use the two to position the element in all the directions:

  • left(-) for left
  • lefft(+) for right
  • top(-) for top
  • top(+) for bottom
  • Top-left: top(-) + left(-)
  • Top-right: top(-) + left(+)
  • Bottom-left: top(+) + left(-)
  • Bottom-right: top(+) + left(+)

Specifically:

  • If b is equal to "left", the left property is decremented by 10 pixels.
  • If b is equal to "right", the left property is incremented by 10 pixels.
  • If b is equal to "up", the top property is decremented by 10 pixels.
  • If b is equal to "down", the top property is incremented by 10 pixels.
  • If b is equal to "top-right", the left property is incremented by 10 pixels and the top property is decremented by 10 pixels.
  • If b is equal to "top-left", the left property is decremented by 10 pixels and the top property is decremented by 10 pixels.
  • If b is equal to "bottom-right", the left property is incremented by 10 pixels and the top property is incremented by 10 pixels.
  • If b is equal to "bottom-left", the left property is decremented by 10 pixels and the top property is incremented by 10 pixels.

Output:

Input Required

This code uses input(). Please provide values below: