Skip to content

Instantly share code, notes, and snippets.

@NickBeeuwsaert
Created December 31, 2013 23:18
Show Gist options
  • Save NickBeeuwsaert/8203263 to your computer and use it in GitHub Desktop.
Save NickBeeuwsaert/8203263 to your computer and use it in GitHub Desktop.
Select! a element
function selectElement(callback){
var selectorDiv = document.createElement("div");
var css = function(e, styles){
for(style in styles){
if(styles.hasOwnProperty(style))
e.style[style.replace(/-(.)/g, function(a,b){return b.toUpperCase();})] = styles[style];
}
};
var pos = function(e){
var pos = {"left": e.offsetLeft, "top": e.offsetTop};
while(e = e.offsetParent){pos.left += e.offsetLeft; pos.top+=e.offsetTop;};
return pos;
};
css(selectorDiv,
{"border": "1px solid hsl(240, 80%, 70%)",
"background": "hsla(240, 50%, 90%,0.5)",
"top":"0",
"left":"0",
"width":"0",
"height": "0",
"display": "none",
"pointer-events":"none",
"position":"absolute",
"z-index": "1000",
"transition": "width 0.5s, height 0.5s, top 0.5s, left 0.5s"});
document.body.appendChild(selectorDiv);
var mouseoverhandler = function(e){
var target = e.target;
if(target == selectorDiv) return;
var p = pos(target);
css(selectorDiv,
{"top":p.top+"px",
"left":p.left+"px",
"display": "block",
"width":(target.offsetWidth-2)+"px",
"height":(target.offsetHeight-2)+"px"});
};
var mousedownhandler = function(e){
e.preventDefault();
e.stopPropagation();
callback(e.target);
document.removeEventListener("mouseover", mouseoverhandler);
document.removeEventListener("mousedown", mousedownhandler);
selectorDiv.parentNode.removeChild(selectorDiv);
return false;
};
document.addEventListener("mouseover", mouseoverhandler);
document.addEventListener("mousedown", mousedownhandler);
};
selectElement(function(e){
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment