views:

171

answers:

3

I want to write a browser (Chrome/FF) extension that needs to select an element on a web page. I would like it to behave like Firebug's element inspector does. You click the inspect arrow and you can then hover/highlight elements. When you click on the element you want, the element is inspected. I'm just interested in the code to allow a user to select an element - not in actually inspecting it or anything similar.

Because I'm writing an extension, it might be nice if you could provide non-jQuery/Prototype/etc.. code so I don't have to distribute that.

+3  A: 

I ended up asking in the Firebug group and got some great help:

http://groups.google.com/group/firebug/browse_thread/thread/7d4bd89537cd24e7/2c9483d699efe257?hl=en#2c9483d699efe257

Chad
Can you the code with us please? I want to do something similar
Vaibhav Garg
+1  A: 

Take a look at SelectorGadget's code.

http://www.selectorgadget.com/

(And it should be more cross browser than firebug's code).

Udi
This looks promising. I don't suppose you're involved with the project?
Chad
No, just a consumer :-)
Udi
+1  A: 

One simple way to do it is to use an outline instead of a border:

.highlight { outline: 4px solid #07C; }

Just add and remove that class to any element you want to select/deselect (code below is not properly tested):

document.body.addEventListener("mouseover", function(e) {
    e.stopPropagation();
    e.target.addEventListener("mouseout", function (e) {
        e.target.className = e.target.className.replace(new RegExp(" highlight\\b", "g"), "");
    });
    e.target.className += " highlight";
}

Since you are using an outline, (which is supported by Chrome) instead of a border, elements will not jump around. I'm using something similar in my EasyReader Extension.

antonj