Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create function in jquery

Tags:

jquery

I am trying to make a jquery function, and used below code, but not getting any output. Please tell me the process to make it.

<script type="text/javascript">
    (function($){
        $.fn.myplugin = function(){
            alert(this.id);
        };
    })(jQuery);

    $("#sample").myplugin();
</script>
like image 690
Dheeraj Agrawal Avatar asked Sep 19 '11 11:09

Dheeraj Agrawal


4 Answers

You can see the working code here – http://jsfiddle.net/gryzzly/YxnEQ/

Note that you need an element with id "sample" to be present in your document when you are running the above code. Also, the this is pointing at jQuery object, so in order to get the elements id, you need to use either of the following:

alert( this[0].id );

or

alert( this.attr('id') );

The first is preferable, because it's faster.

like image 123
Misha Reyzlin Avatar answered Sep 19 '22 17:09

Misha Reyzlin


Try this:

<script type="text/javascript">
 $(document).ready(function(){
  myplugin($("#sample"));
 });

  function myplugin(obj){
  alert(obj.id);
  }
</script>
like image 32
ip_x Avatar answered Sep 17 '22 17:09

ip_x


Try this:

<script type="text/javascript">
$(document).ready(function(){
    $("#sample").myplugin(this.id);
});

function myplugin(id) {
    alert(id);
}
</script>
like image 27
Kanishka Panamaldeniya Avatar answered Sep 18 '22 17:09

Kanishka Panamaldeniya


Try changing

        alert(this.id);

to

        alert(this[0].id);

As you're getting a jQuery object array.

like image 37
Dogbert Avatar answered Sep 18 '22 17:09

Dogbert