Advertisement
antijingoist

Quick and Dirty alt text tool tips

Dec 2nd, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.35 KB | Source Code | 0 0
  1. var styles = `
  2.     #imageAltTip {
  3.       position: fixed;
  4.       top: 0;
  5.       left: 0;
  6.       min-height: 2rem;
  7.       height: fit-content;
  8.       width: fit-content;
  9.       background: black;
  10.       color: white;
  11.       display: none;
  12.       z-index: 99999;
  13.       padding: 5px 1rem;
  14.     }
  15.  
  16.   #imageAltTip.alt-ToolTipShow {
  17.     display: block;
  18.   }
  19. `
  20.  
  21. var styleSheet = document.createElement("style")
  22. styleSheet.textContent = styles
  23. document.head.appendChild(styleSheet);
  24.  
  25. altTip = document.createElement("div");
  26. altTip.setAttribute("id", "imageAltTip");
  27. altTip.innerHTML = "";
  28. document.body.append(altTip);
  29.  
  30. var imageNodes = document.getElementsByTagName("img");
  31. for (var i = 0; i < imageNodes.length; i++) {
  32.   document.images[i].addEventListener(
  33.     "mouseover",
  34.     function (e) {
  35.       altTip.className = "";
  36.     }, false );
  37. }
  38.  
  39.  
  40. for (var i = 0; i < imageNodes.length; i++) {
  41.   document.images[i].addEventListener(
  42.     "mousemove",
  43.     function (e) {
  44.       altTip.className = "alt-ToolTipShow";
  45.       altTip.style.left = (e.clientX) + "px";
  46.       altTip.style.top = e.clientY + "px";
  47.  
  48.       try {
  49.         altTip.innerHTML = e.srcElement.alt;
  50.       } catch(e) {
  51.         try {
  52.           altTip.innerHTML = e.srcElement.title;
  53.         } catch(e) {
  54.           altTip.innerHTML = "No alt text";
  55.         }
  56.       }
  57.     },
  58.     false,
  59.   );
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement