Hover Image in LWC

In this blog we will see how we can make our clickable images more interactive in LWC.

Consider we have a lot of images on our component and each of them display some data when clicked/accessed. But for a user to figure out which element was clicked, it is always good to make those elements interactive.

To achieve this, I have used four images, 2 for each. One being the actual and the other being exact inverted. I then switch between those images during mouseover and mouseout events.

<template>
    <table style="background-color:#0B2233; width:100%;" >
        <tr style="height: 50%; table-layout: fixed; width:50%">
            <td style="width: 50%;">
                <table>
                    <tr>
                        <td style="width: 25%;"><img src={redCar} onmouseover={mouseOver} onmouseout={mouseOut} data-id="RedCar" /></td>
                        <td style="width: 25%;"></td>
                        <td style="width: 25%;"></td>
                        <td style="width: 25%;"></td>
                    </tr>
                    <tr>
                        <td style="width: 25%;"></td>
                        <td style="width: 25%;"><img src={greenCar} onmouseover={mouseOver} onmouseout={mouseOut} data-id="GreenCar" /></td>
                        <td style="width: 25%;"></td>
                        <td style="width: 25%;"></td>
                    </tr>
                </table> 
            </td>
        </tr>
    </table>
</template>
import { LightningElement } from 'lwc';
import SVG_CarGreen from '@salesforce/resourceUrl/GreenCar';
import SVG_CarGreenHover from '@salesforce/resourceUrl/GreenCarHover';
import SVG_CarRed from '@salesforce/resourceUrl/RedCar';
import SVG_CarRedHover from '@salesforce/resourceUrl/RedCarHover';

export default class HoverImages extends LightningElement {
    greenCar = SVG_CarGreen;
    greenCarHover = SVG_CarGreenHover;
    redCar = SVG_CarRed;
    redCarHover = SVG_CarRedHover;

    mouseOver (evt) {
        var dataId = evt.target.getAttribute('data-id');

        switch(dataId) {
            case "GreenCar":
                this.template.querySelector(`[data-id="${dataId}"]`).src = this.greenCarHover;
              break;
            case "RedCar":
                this.template.querySelector(`[data-id="${dataId}"]`).src = this.redCarHover;
              break;
        }
    }

    mouseOut (evt) {
        var dataId = evt.target.getAttribute('data-id');

        switch(dataId) {
            case "GreenCar":
                this.template.querySelector(`[data-id="${dataId}"]`).src = this.greenCar;
              break;
            case "RedCar":
                this.template.querySelector(`[data-id="${dataId}"]`).src = this.redCar;
              break;
        }
    }
}

Leave a Reply

%d bloggers like this: