highlight a DOM element on mouse over, like inspect does

Ionut Flavius Pogacian picture Ionut Flavius Pogacian · Jun 13, 2012 · Viewed 16.7k times · Source

We have a bookmarklet, and the user clicks a button and an inspect like highligther needs to kick in. We want to this to be cross browser.

For this we need to detect the DOM element during the mouse move, and once we have this element we need to highlight with CSS.

We have problems detecting the DOM element by mouse move, can you guide us how this is done?

Once we have this DOM element, on user click we need to extract XPath.

Answer

T.J. Crowder picture T.J. Crowder · Jun 13, 2012

You can hook mousemove on document or document.body, then use the target property of the event object to find out the topmost element the mouse is over. Then applying CSS to it is probably most easily done by adding a class to it.

But I wonder if the :hover psuedo-class might save you some trouble...

If not using :hover, here's an example:

(function() {
  var prev;

  if (document.body.addEventListener) {
    document.body.addEventListener('mouseover', handler, false);
  }
  else if (document.body.attachEvent) {
    document.body.attachEvent('mouseover', function(e) {
      return handler(e || window.event);
    });
  }
  else {
    document.body.onmouseover = handler;
  }

  function handler(event) {
    if (event.target === document.body ||
        (prev && prev === event.target)) {
      return;
    }
    if (prev) {
      prev.className = prev.className.replace(/\bhighlight\b/, '');
      prev = undefined;
    }
    if (event.target) {
      prev = event.target;
      prev.className += " highlight";
    }
  }

})();

Live copy | source