Jquery writing unobtrusive javascript help

I have the following code in jquery.

$(function() {
  $('.test').click(function() {
    alert('this is a test');
  });
});

I understand that this is unobtrusive, but I would like to try to make it even more unobtrusive by doing something like this.

$(function() {
  $('.test').submitAlert();

 *and place the alert message right here.
});

Then I could trigger a warning message on different classes without re-entering the code. Can someone please show how to do this with me using jquery?

+3
source share
1 answer

You can insert your code into the plugin:

(function($) {
    $.fn.submitAlert = function(text) {
        this.bind("click", function() {
            alert(text);
        });
    }
})(jQuery);

Using:

$(".test").submitAlert("hello world");

Here is a working example: http://jsfiddle.net/andrewwhitaker/UGsHR/1/

+8
source

All Articles