/ Gists / Alpine - magic (custom method)
On gists

Alpine - magic (custom method)

Alpine.js

overlap.js Raw #

// https://github.com/markmead/alpinejs-overlap/blob/main/src/index.js

export default function (Alpine) {
  Alpine.magic('overlap', (el, {}) => (targetId) => {
    const targetEl = document.querySelector(targetId)

    return checkOverlap(
      targetEl.getBoundingClientRect(),
      el.getBoundingClientRect()
    )
  })

  function checkOverlap(targetBounding, elBounding) {
    return !(
      targetBounding.top > elBounding.bottom ||
      targetBounding.right < elBounding.left ||
      targetBounding.bottom < elBounding.top ||
      targetBounding.left > elBounding.right
    )
  }
}

example.html Raw #

<div class="relative">
  <div id="TargetEl" class="w-32 h-32 bg-teal-700 rounded-lg"></div>

  <div
    x-data="{ isOverlap: $overlap('#TargetEl') }"
    x-on:resize.window="isOverlap = $overlap('#TargetEl')"
    :class="{ 'bg-red-700': isOverlap, 'bg-teal-700': !isOverlap }"
    class="absolute inset-y-0 right-0 grid w-32 h-32 rounded-lg place-content-center"
  >
    <p
      x-text="isOverlap ? 'Overlapping' : 'Will Overlap'"
      class="text-sm font-medium text-white"
    ></p>
  </div>
</div>