sumnima sumnima sumnima sumnima sumnima sumnima sumnima
Categories
blog javascript

emoji cursors!

document.addEventListener("DOMContentLoaded", function() {
  // run only on archive/category pages
  if (!document.body.classList.contains("archive") || !document.body.classList.contains("category")) return;

  const emojis = [
    "🧸","🎈","🍭","🪁","🐻","🐼","🐨","🦄","🍦","🐰",
    "🌼","🌸","🌺","🌻","🌷",
    "🎨","🛷",
    "🍉","🍓","🌈"
  ];

  const articles = document.querySelectorAll("article.type-post");

  articles.forEach((article, i) => {
    // assign one emoji per article
    const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];

    // build and encode SVG containing the emoji
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
                   <text y="80" font-size="80">${randomEmoji}</text>
                 </svg>`;
    const encoded = encodeURIComponent(svg);

    // make a unique class for this article
    const className = `emoji-cursor-${i}`;

    // create a style rule that applies the cursor to the article AND ALL ITS CHILDREN
    const styleEl = document.createElement('style');
    styleEl.textContent = `.${className}, .${className} * { cursor: url("data:image/svg+xml;utf8,${encoded}"), auto !important; }`;
    document.head.appendChild(styleEl);

    // toggle the class on hover so the cursor appears/disappears reliably
    article.addEventListener('mouseenter', () => article.classList.add(className));
    article.addEventListener('mouseleave', () => article.classList.remove(className));
  });
});