1

I have written 1-2 jquery plugins but all of them fails when i try to use multiple instances....i didnt find any solution. Please take a look at below code, if u create 2 instances on this plugin its not working....whats wrong with this code. what makes plugin able to run multiple instances ??

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
 <head>
 </head>
 <script src="jquery.js"></script>
 <script>
     (function($){  
     $.fn.truncate = function(options) {  

      return this.each(function() {  
       obj = $(this);  
       var body = obj.html();  

    $(obj).focus(function(){
       alert($(obj).attr("id"));
    });    

      });  
     };  
    })(jQuery);
    </script>
 <SCRIPT LANGUAGE="JavaScript">
 <!--
   $().ready(function(){  
    $('#t1').truncate();
    $('#t2').truncate();
   });    
 //-->
 </SCRIPT>
 <body>
   <input type="text" id="t1">
   <input type="text" id="t2">
 </body>
</html>

3 Answers 3

4

The problem is right here:

return this.each(function() {  
    obj = $(this);  
    …

You forgot to declare obj with var. It will be a global variable — and will get overwritten each time .truncate() is called. This should work better:

return this.each(function() {  
    var obj = $(this);  
    …

By the way, calling .ready() on an empty jQuery object ($()) is officially not recommended. Use this:

$(function(){
    …
});

or this:

$(document).ready(function(){
    …
});

instead.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this as a foundation..

(function($){  
     $.fn.truncate = function(){  

          this.each(function(){  

              //work on each element here
              console.log($(this).attr('id'));

          });

          return this;

     };  
})(jQuery);





$(document).ready(function(){  
    $('#t1,#t2').truncate();
}); 

1 Comment

Ahhhaaaa this is much clear now...i even tried adding options too...its working...Thanks friend.....i will not go further to implement it in my plugin, right now it only supports single instance.
0
$(document).ready(function(){  
    $('#t1').truncate();
    $('#t2').truncate();
   });    

This might help: http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

Comments

Your Answer

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.