toddmotto / echo

Lazy-loading images with data-* attributes

Home Page:http://toddmotto.com/labs/echo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Callback for a manually set tag

flamez-b opened this issue · comments

Thank you for the plugin. I works fine! At the moment I use it to pull images and set a class for them with the way like this:
echo.init({
offset: 100,
throttle: 1,
unload: false,
callback: function (element, op) {
element.className = "fade-in";
}
});

I would also like to set a special class for some tags which come into view when scrolling (a kind of inView feature). Is there a correct way to do this?

// Initialize echo.js as you normally do
echo.init({
  offset: 100,
  throttle: 1,
  unload: false,
  callback: function (element, op) {
    element.className = "fade-in";
  }
});

// Your custom function to add a class to specific tags
function handleInView(element) {
  if (isElementInView(element)) {
    element.classList.add("special-class");
  }
}

// Function to check if an element is in view
function isElementInView(element) {
  var rect = element.getBoundingClientRect();
  return (
    rect.bottom >= 0 &&
    rect.right >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.left <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

// Example usage
var specialElements = document.querySelectorAll(".your-special-tag");

specialElements.forEach(function (element) {
  handleInView(element);
});

// Attach a scroll event listener to check for elements in view while scrolling
window.addEventListener("scroll", function () {
  specialElements.forEach(function (element) {
    handleInView(element);
  });
});