BreakPoint Images is a simple JavaScript plugin to swap images out based on viewport width stored as JSON in a data attribute.
BreakPoint Images does not have any dependicies on any existing JavaScript framework. This really works best for responsive websites where you expect users to either be switching the orientation of their device or resizing the browser window. A lot of other viewport-based JS based scripts assume that each image loaded on each breakpoint will be the same aspect ratio. Most will load the largest image when viewed in the largest viewport setting, but not swap the image with the version meant for a smaller breakpoint when the viewport is scaled back down. This script will ensure that the proper image is loaded on its breakpoint when loaded and when scaled up or down.
This script really works well when your loading your images dynamically, like through Drupal with Imagecache settings or WordPress using their thumbnail, medium, and large images sizes.
The meat of this script is in the data attributes on the wrapping <span>
tag.
- data-alt: The
alt
attribute to apply to your image - data-title: The
title
attribute to apply to your image - data-src: The JSON object containing your breakpoint image data. It accepts 2 key/value pairs:
- bp: The breakpoint in pixels you want this image to react to
- url: The path to the image to want to swap
- Include breakpoint-images.min.js at the bottom of your web page.
- Add your default image tag with a
<noscript>
tag around it. - Wrap that in a
<span>
with the class "r-img". - Add 3 data attributes with desired data.