Attach absolutely positioned elements to other elements

The dev team at HubSpot has created a JavaScript library that lets you tether absolutely positioned elements to other elements.

Marrying elements for life

No more fighting with viewports and scroll positions. Tether lets you attach, or tether, elements with a single line of code—and it has some powerful extras.

Tether includes the ability to constrain the element within the viewport, its scroll parent, any other element on the page, or a fixed bounding box. When it exceeds those constraints it can be pinned to the edge, flip to the other side of its target, or hide itself.

Here's an example from their project page:

new Tether({
  element: yellowBox,
  target: greenBox,
  attachment: 'top right',
  targetAttachment: 'top left'
});

The code is pretty simple: element is what your attaching and target is the element you're attaching it to. Both attachment and targetAttachment are anchor points that tell Tether how and where to join the objects. (For more flexibility, there are some other settings you can explore in the documentation.)

Once instantiated, yellowBox will follow greenBox as you scroll through the page, resize the window, etc. Not bad for a 5kb (minified) library. Works in all modern browsers, and IE9+.

So what's the magic?

I was hoping that the developers found some clever way to efficiently poll the DOM, but it's not that amazing. Tether works by simply repositioning each tethered element when the page is resized or when any of the parent elements are scrolled. If you're moving things around with JavaScript, you'll have to make a call to Tether.position() to tell it to redraw.

Still, this is a handy library to have if you loathe cross browser viewport and scroll position math.

Built with Tether

The HubSpot developers also released a few plugins that were built with Tether.

  • Select - styleable select elements
  • Drop - fast and capable dropdowns
  • Tooltip - styleable tooltips
  • Shepherd - a guided tour for your users

What will you build, or what have you built in the past that would benefit from Tether?

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.