SO fiddle
Test Fiddle mainly for SO Questions
by Nick Craver
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/themes/overcast/jquery-ui.css">
<div id="someElement">Test</div>
<button>Click me</button>
CSS
a { padding: 5px; cursor: pointer; }
a:hover { color: blue; }
JavaScript
(function ($) {
$.fn.myPlugin = function (action) {
action = action || "initialize";
if (action == "getSelection") {
return this.data('index');
}
return this.each(function ($this) {
$this = $(this);
if (action == "initialize") {
$this.html('<div></div>');
var div = $("div", $this);
div.append('<a>A</a>').append('<a>B</a>').append('<a>C</a>');
div.children("a").each(function (i) {
$(this).click(function (event) {
// Here I store the index.
$this.data('index', $(this).index());
event.preventDefault();
return false;
});
});
return $this;
}
});
};
})(jQuery);
$("#someElement").myPlugin();
$("button").click(function() {
alert($("#someElement").myPlugin("getSelection"));
});