Skip to content

Instantly share code, notes, and snippets.

@bbarth
Forked from cowboy/delegate-refactor.js
Created April 2, 2011 16:52
Show Gist options
  • Save bbarth/899638 to your computer and use it in GitHub Desktop.
Save bbarth/899638 to your computer and use it in GitHub Desktop.
// BEFORE
// http://jsfiddle.net/markcoleman/ffBcU/11/
var currentColor = "white";
var hold = false;
$(".canvas")
.delegate(".pixel", "mouseover", function() {
$(this).css("background-color", currentColor);
})
.delegate(".pixel", "mouseout", function() {
if (!$(this).data("painted")) {
$(this).css("background-color", "");
}
if ($(this).data("painted")) {
$(this).css("background-color", $(this).data("painted"));
}
})
.delegate(".pixel", "mousedown", function() {
hold = true;
$(this).css("background-color", currentColor).data("painted", currentColor);
})
.delegate(".pixel", "mouseup", function() {
hold = false;
})
.delegate(".pixel", "mousemove", function(e) {
if (hold) {
var elem = document.elementFromPoint(e.pageX, e.pageY);
if ($(elem).is(".pixel")) {
$(elem).css("background-color", currentColor).data("painted", currentColor);
}
}
});
// AFTER
// http://jsfiddle.net/cowboy/ffBcU/12/
var currentColor = "white";
var hold = false;
$(".canvas")
.delegate(".pixel", "mouseover mouseout", function( e ) {
var color = e.type == "mouseover" ? currentColor : $(this).data("painted") || "";
$(this).css("background-color", color);
})
.delegate(".pixel", "mousedown mouseup", function( e ) {
hold = e.type == "mousedown";
})
.delegate(".pixel", "mousedown mousemove", function() {
hold && $(this).css("background-color", currentColor).data("painted", currentColor);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment