Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    aku
    aku is offline
    New Coder
    Join Date
    Jan 2007
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    [HELP] Javascript OO function scope

    Hi guys,

    I made this script in OO, for animated toggle effect. But when i try to use the script return an error arrived at 'this.obj.style.overflow = 'hidden' ;' and it sad that this.obj has not properties. I think this cause window.setInterval execute the function this.collapse in a scope where this.obj it's not defined.
    How can i fix this error using the same syntax ( not referencing variables ) ?

    i'm sorry for my wrong english!! :P



    Code:
    function Toggle ( trigger, obj, speed ) {
    
    	this.intervalId = null ;
    	this.trigger = trigger ;
    	this.obj = obj ;
    	this.speed = speed ;
    
    	this.create = function () {
    		window.clearInterval ( this.intervalId ) ;
    		if ( !this.speed )
    			this.speed = parseInt ( 100 / 30 )  ;
    		if ( !this.obj.style.display ) {
    			this.trigger.innerHTML = '+' ;
    			this.intervalId = window.setInterval ( this.collapse, 1 ) ;
    		}
    		else {
    			this.trigger.innerHTML = '-' ;
    			this.intervalId = window.setInterval ( this.expand, 1 ) ;
    		}
    	}
    
    	this.expand = function () {
    		this.obj.style.display = '' ;
    		if ( this.getHeight () < 100 ) {
    			this.obj.style.height = this.getHeight () + this.speed + 'px' ;
    		}
    		else {
    			this.obj.style.height = 100 + 'px' ;
    			window.clearInterval ( this.intervalId ) ;
    		}
    	}
    
    	this.collapse = function () {
    		this.obj.style.overflow = 'hidden' ;
    		if ( this.getHeight () > 0 ) {
    			if ( this.speed > this.getHeight () )
    				this.obj.style.height = 0 + 'px' ;
    			else
    				this.obj.style.height = this.getHeight () - this.speed + 'px' ;
    		}
    		else {
    			this.obj.style.display = 'none' ;
    			window.clearInterval ( this.intervalId ) ;
    		}
    	}
    	
    	this.getHeight = function () {
    		return this.obj.offsetHeight ;
    	}
    
    }

  • #2
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    create closure (or whatever thats called...) like this

    Code:
    this.intervalId = window.setInterval ( function() {
        this.collapse();
        // or if that doesn't do the trick
       // this.collapse.apply(this); // this is overkill :)
    }, 1 ) ;


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •