7

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>
Lightness Races in Orbit
387k77 gold badges672 silver badges1.1k bronze badges
asked Sep 19, 2011 at 11:55
1
  • do you have the element with an id "sample" somewhere in your document? is this script tag placed below the HTML? if not, wrap the code with $(document).ready(function() { // here goes your code }); Commented Sep 19, 2011 at 12:12

5 Answers 5

11

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.

answered Sep 19, 2011 at 12:06
Sign up to request clarification or add additional context in comments.

1 Comment

what browser you are in? is jQuery loaded on the page?
5

Try this:

<script type="text/javascript">
 $(document).ready(function(){
 myplugin($("#sample"));
 });
 function myplugin(obj){
 alert(obj.id);
 }
</script>
answered Nov 29, 2012 at 10:26

1 Comment

Actually i was not able to workout solution given by @Kanishka , so this answer is an improvement to his solution .Just thought of sharing it
3

Try this:

<script type="text/javascript">
$(document).ready(function(){
 $("#sample").myplugin(this.id);
});
function myplugin(id) {
 alert(id);
}
</script>
answered Sep 19, 2011 at 12:01

Comments

1

Try changing

 alert(this.id);

to

 alert(this[0].id);

As you're getting a jQuery object array.

answered Sep 19, 2011 at 12:00

Comments

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

this in that context is a jQuery object, not a raw DOM element.

answered Sep 19, 2011 at 12:00

1 Comment

so what should be the code & how I will implement any jquery function?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.