Google Chrome Extension: highlight the div that the mouse is hovering over

user425445 picture user425445 · Dec 14, 2010 · Viewed 15.7k times · Source

I am new to Google Chrome extensions and trying to write an extension that highlights a div on hover. If there is a div inside another div and inner div is hovered, I would like to highlight the internal div only.

I have got some of the samples working but I'm not sure how to catch the hover event.

Answer

Mohamed Mansour picture Mohamed Mansour · Dec 15, 2010

In HTML, every mouse event has access to the underlying element. You can do that easily with JavaScript, and there is a nice feature in HTML5 called classList (thanks to Erik from Chromium) that allows you to add and remove classes from DOM's easily.

First of all, you can achieve this with Google Chrome's Content Scripts. The algorithm is quite straightforward, you keep a pointer to the last visited DOM, and you just add/remove class's when you visit another DIV element.

Within your manifest.json We will define the CSS and JS injections to every page we see.

 ...
  ...
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "css": ["core.css"],
      "js": ["core.js"],
      "run_at": "document_end",
      "all_frames": true
    }
  ]
  ...
  ...

Now lets look into our core.js, I have included some comments to explain what is going on:

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';

// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;

// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
  var srcElement = e.srcElement;

  // Lets check if our underlying element is a DIV.
  if (srcElement.nodeName == 'DIV') {

    // For NPE checking, we check safely. We need to remove the class name
    // Since we will be styling the new one after.
    if (prevDOM != null) {
      prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
    }

    // Add a visited class name to the element. So we can style it.
    srcElement.classList.add(MOUSE_VISITED_CLASSNAME);

    // The current element is now the previous. So we can remove the class
    // during the next iteration.
    prevDOM = srcElement;
  }
}, false);

Now, lets look at the simple core.css for the styles:

.crx_mouse_visited {
  background-color: #bcd5eb !important;
  outline: 1px solid #5166bb !important;
}

Thats it, you will notice that all your divs will have a "hovered" state, similar on what happens when you visit your browser inspector when inspecting elements.