public
Last active

Javascript function that adds a little surprise to your HTML elements.

  • Download Gist
robotButton.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
function initRobotButton(item,clicked_fn) {
item.after('<div id="littlerobot123asdf">&nbsp;</div>');
lilrobot = $('#littlerobot123asdf');
lilrobot.css({ "z-index": 3, "background-position": "0px -540px", "position": "absolute", "background-image": "url(/images/robot_sprites_sm.png)", "font-size": "0em", "padding": "85px 75px 0px 0px", "background-repeat": "no-repeat" });
item.css({ "z-index": 4, "position": "absolute"});
var notclicked = true;
item_loc = item.offset();
item_dim = { h: item.height(), w: item.width() };
item_center = { y: item_loc.top + (item_dim.h / 2), x: item_loc.left + (item_dim.w / 2) }
lilrobot.offset({top: item.offset().top - 80, left: item.offset().left + (item_dim.w / 2)});
$(document).mousemove(function(e) {
if(notclicked) {
item_loc = item.offset();
item_dim = { h: item.height(), w: item.width() };
item_center = { y: item_loc.top + (item_dim.h / 2), x: item_loc.left + (item_dim.w / 2) }
lilrobot.offset({top: item.offset().top - 80, left: item.offset().left + (item_dim.w / 2)});
distY = Math.abs(e.pageY - item_center.y) - (item_dim.h/2);
distX = Math.abs(e.pageX - item_center.x) - (item_dim.w/2);
dist = (distY < distX ? distX : distY);
if(distX < 200 && distY < 200)
lilrobot.css("background-position", "0px " + ((dist/200)*80) + "px");
else
lilrobot.css("background-position", "0px -540px");
}
})
item.click(function(e) {
notclicked = false;
lilrobot.css("background-position", "-80px 0px");
if(clicked_fn != null)
clicked_fn();
});
}

Issues:

FIFY: https://gist.github.com/1339425

Didn't fify:

  • Use a class instead of .css. Changing css is painfully slow in the DOM instead of changing the class (which is up to 95% faster).
  • Semantically this should be a plugin, and support the selector rather than locked to IDs.
  • Probably better suited to a smaller library such as zepto or ender JS for better performance, they're mostly designed to mimic the jQuery API.
  • You need to be careful, if you implement this on too many elements your browser's going to cry dealing with all of the events being bound multiple times (each call of this implements a new mousemove event, so your demo page is doing the same thing 10 times, if it did it once you could scale it out to dozens of these), Similar issue for .click exists, but less damaging as it's bound to the specific element (where as document gets bound the event n times).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.