MediaWiki:Gadget-Tooltip.js

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 05:20, 1 June 2024 by Vish (talk | contribs)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
$(document).ready(function() {
    var popups = document.querySelectorAll('.popup');

    Array.prototype.forEach.call(popups, function(popup) {
        // Create and append the popup box
        var popupBox = document.createElement('div');
        popupBox.classList.add('popup-box');
        popupBox.textContent = popup.getAttribute('data-content');
        popup.parentNode.appendChild(popupBox); // Append as sibling to the popup span

        var isClickedOpen = false;

        function positionPopupBox() {
            popupBox.style.position = 'absolute';
            popupBox.style.top = popup.offsetHeight + 'px'; // Position below the popup span
            popupBox.style.left = '0'; // Align to the left of the popup span
        }

        function togglePopupVisibility() {
            var rect = popup.getBoundingClientRect();
            // Check if the popup span is within the viewport
            if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
                popupBox.style.display = 'block';
            } else {
                popupBox.style.display = 'none';
            }
        }

        // Event listeners for mouse enter, leave and clicks
        popup.addEventListener('mouseenter', function() {
            positionPopupBox();
            popupBox.style.display = 'block';
        });

        popup.addEventListener('mouseleave', function() {
            if (!isClickedOpen) {
                popupBox.style.display = 'none';
            }
        });

        popup.addEventListener('click', function(event) {
            event.stopPropagation();
            isClickedOpen = !isClickedOpen;
            popupBox.style.display = isClickedOpen ? 'block' : 'none';
        });

        popupBox.addEventListener('click', function(event) {
            event.stopPropagation(); // Prevent closing on click inside
        });

        // Check popup visibility on scroll and resize
        window.addEventListener('scroll', togglePopupVisibility);
        window.addEventListener('resize', togglePopupVisibility);

        // Clicking outside the popup closes it
        document.addEventListener('click', function(event) {
            if (!popup.contains(event.target) && !popupBox.contains(event.target)) {
                popupBox.style.display = 'none';
                isClickedOpen = false;
            }
        });
    });
});