Created
July 3, 2012 18:11
-
-
Save daifu/3041475 to your computer and use it in GitHub Desktop.
Javascript Web Application: Delegation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery.fn.tabs = function(control){ | |
var element = $(this); | |
control = $(control); | |
element.delegate("li", "click", function(){ | |
// Retrieve tab name | |
var tabName = $(this).attr("data-tab"); | |
// Fire custom event on tab click | |
element.trigger("change.tabs", tabName); | |
}); | |
// Bind to custom event | |
element.bind("change.tabs", function(e, tabName){ | |
element.find("li").removeClass("active"); | |
element.find(">[data-tab='" + tabName + "']").addClass("active"); | |
}); | |
element.bind("change.tabs", function(e, tabName){ | |
control.find(">[data-tab]").removeClass("active"); | |
control.find(">[data-tab='" + tabName + "']").addClass("active"); | |
}); | |
// Activate first tab | |
var firstName = element.find("li:first").attr("data-tab"); | |
element.trigger("change.tabs", firstName); | |
return this; | |
}; | |
// Example of usage | |
$("#tabs").trigger("change.tabs", "users"); | |
// Example of extend the plugin. | |
$("#tabs").bind("change.tabs", function(e, tabName){ | |
window.location.hash = tabName; | |
}); | |
$(window).bind("hashchange", function(){ | |
var tabName = window.location.hash.slice(1); | |
$("#tabs").trigger("change.tabs", tabName); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment