jQuery obj vs HTML element has nothing to do with it. When you fire
the function with setInterval or setTimeout it is executed in the
global scope, so 'this' doesn't refer to the current object anymore,
that was the problem.

Just for fun, how about this to simplify it?

jQuery.fn.JSClock = function() {
  var self = this;
  function pad(i) {
      return (i < 10) ? '0'+i : i;
  };
  setInterval(function(){
     var t = new Date();
     self.text("Local Time: "+t.getHours()+":"+pad( t.getMinutes() )
+":"+pad( t.getSeconds() );
  }, 1000);
};

Or this to make it more complex? :)
(has the advantage of starting immediately)

jQuery.fn.JSClock = function() {
  var self = this;
  (function(){
    var time = "Local Time: _Hours:_Minutes:_Seconds".replace(/_(\w+)/
g, function(a,b){
      var d = new Date()['get'+b]()
        return d<10 ? '0'+d : d;
      });
      self.text( time );
      setTimeout(arguments.callee, 1000);
  })();
};

I better get back to work...

On Apr 23, 4:20 am, Joseph Le Brech <jlebr...@hotmail.com> wrote:
> I often find that sometimes $(this).html will work.
>
>
>
> > Date: Wed, 22 Apr 2009 19:49:13 -0700
> > Subject: [jQuery] Re: Infinite Recall Over a Fixed Interval
> > From: kiu...@mac.com
> > To: jquery-en@googlegroups.com
>
> > On Apr 22, 5:29 pm, James <james.gp....@gmail.com> wrote:
> > > Something like the below?
>
> > > (function($) {
> > >                   $.fn.JSClock = function() {
> > >                           setInterval(function() {
> > >                                // code to get and write time here
> > >                           }, 1000);
> > >                    }
> > > > })(jQuery);
>
> > In and of themselves the above and the following both fail. My guess
> > is that this.html() object is not a proper reference.  I say this,
> > because the code JSClock() does not interfere with the rest of my
> > jQuery methods when placed inside the $.ready( ) method.
>
> > (function($) {
> >    $.fn.JSClock = function() {
> >            function timeFormat(i) {
> >                    if (i < 10) {
> >                            i="0" + i;
> >                    }
> >            return i;
> >            }
> >            setInterval(function() {
> >                    var today=new Date();
> >                    var h=today.getHours();
> >                    var m=today.getMinutes();
> >                    var s=today.getSeconds();
> >                    m=timeFormat(m);
> >                    s=timeFormat(s);
> >                    this.html("Local Time: " + h +":"+ m +":"+s);
> >            },500);
> >    }
> > })(jQuery);
>
> > $(document).ready(function() {
> >    $('#flowers').writeColorOfFlower();
> >    $('#today').toDate();
> >    $('#clock').JSClock();
> > });
>
> _________________________________________________________________
> View your Twitter and Flickr updates from one place – Learn 
> more!http://clk.atdmt.com/UKM/go/137984870/direct/01/

Reply via email to