Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FocusPoint JS Using Picture Element
<div class="focuspoint"
role="presentation"
data-focus-x-sm="-0.27" data-focus-y-sm="0.98" data-image-w-sm="992" data-image-h-sm="685"
data-focus-x-md="-0.29" data-focus-y-md="1.00" data-image-w-md="1102" data-image-h-md="809"
data-focus-x-lg="-0.05" data-focus-y-lg="1.00" data-image-w-lg="1600" data-image-h-lg="879"
>
<picture class="img-presentation">
<source media="(min-width: 1200px)" srcset="http://cdn.com/path/to/marquee-lg.jpg">
<source media="(min-width: 992px)" srcset="http://cdn.com/path/to/marquee-md.jpg">
<source media="(min-width: 768px)" srcset="http://cdn.com/path/to/marquee-sm.jpg">
<img src="http://cdn.com/path/to/marquee-sm.jpg">
</picture>
</div>
// Note: Class and other code omitted for berevity,
// Note: ES6
// Note: Focus Point Version: 1.1.3
// Called by custom media query change listeners based on MatchMedia API
// Executes when the browser crosses a media query in either direction
function onMediaQueryChange() {
const $imgContainer = $(".focuspoint"); // already initialized focuspoint by here (see docs)
const mqSuffix = getMqSuffix(); // custom functionality (returns "sm", "md", "lg")
const focusX = $imgContainer.attr(`data-focus-x-${mqSuffix}`);
const focusY = $imgContainer.attr(`data-focus-y-${mqSuffix}`);
const imageW = $imgContainer.attr(`data-image-w-${mqSuffix}`);
const imageH = $imgContainer.attr(`data-image-H-${mqSuffix}`);
// Inject custom data into
$imgContainer.data({focusX, focusY, imageW, imageH});
$imgContainer.focusPoint("adjustFocus");
}

Repo

https://github.com/jonom/jquery-focuspoint

Notes

  • This solve is useful for a fluid layout; where art-direction for every possible width is not practical.
  • Picture element setup is fairly simple:
    • Adhears to Bootstrap 3 breakpoints
    • Source elements use a single value for srcset
  • onMediaQueryChange is called by some custom MatchMedia based code, which isn't hard to write
  • getMqSuffix simply checks the current breakpoint and returns "sm", "md", or "lg".
  • I created the values for each version of the data- attrs using the nice helper tool linked to from the repo.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment