/BreakPoint-Images

BreakPoint Images

Primary LanguageJavaScript

BreakPoint Images

BreakPoint Images is a simple JavaScript plugin to swap images out based on viewport width stored as JSON in a data attribute.

VIEW THE DEMO HERE

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.

There are 3 data attributes used:

  • 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

EXAMPLE USAGE:

3 Breakpoints: 420, 820, & 1100

7 Breakpoints: 420, 520, 620, 720, 820, 920 & 1020


STEPS TO USE:

  1. Include breakpoint-images.min.js at the bottom of your web page.
  2. Add your default image tag with a <noscript> tag around it.
  3. Wrap that in a <span> with the class "r-img".
  4. Add 3 data attributes with desired data.