A generic library to swap out an image on hover.
yarn add @designory/hover-image # or npm install @designory/hover-image
Place your configured
hoverSrcAttribute (which defaults to
If you place the attribute on a tag that isn't an
<img>, then we search for the first child
<img> tag to have its source swapped.
When you hover over this link, the icon will change.
The child image is found using
querySelector, which uses a "depth-first pre-order traversal" of the child nodes. If you have many child image nodes, and you don't want the first one, you can also put an additional data attribute to specify a selector.
This data attribute is configured by the
hoverImageSelectorAttribute option, and defaults to
When you hover over this link, the icon on the left will remain the same, the icon to the right instead will change.
Once your HTML is configured, you need to initialize the mouse event listeners:
;// Or, if non-transpiled:// const initializeHoverImage = require('@designory/hover-image');;
The initialize function returns a
destroy function if you need to remove
the event listeners that get added:
let destroyHoverListeners = ;;
Additionally, hover-image is published as a UMD module and so can be used directly in a browser context. When loading the UMD module, it is exposed under
The data attribute the library will attach its delegated events to.
This can be placed on any element, not just on an
<img> tag. If this is placed on a non-image tag, then we look for the first child
<img> of that element. If you need to target a child element other than the first matching
img, then see the
hoverImageSelectorAttribute option for more information on how to pass a custom selector.
The name of the data attribute the library will save the original source URL while the image is swapped out.
hoverSrcAttribute is placed on a non-image element, this optional attribute allows for a selector to be passed for the child image that'll be swapped out. When this attribute is not present, the selector it uses is
The class that will get toggled while the image is swapped out on hover.
When true, will make a network request for all images specified within the
hoverSrcAttribute before the initial
mouseover event has fired. If the browser is caching network requests, this should help eliminate the slight empty flash the user sees when hovering over the image for the first time.
- Internet Explorer (IE) 10
- All modern browsers