Skip to content

Instantly share code, notes, and snippets.

@joshuasiler
Created November 2, 2011 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joshuasiler/1332343 to your computer and use it in GitHub Desktop.
Save joshuasiler/1332343 to your computer and use it in GitHub Desktop.
Javascript function that adds a little surprise to your HTML elements.
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();
});
}
@Incognito
Copy link

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment