The Furious Bear
The Furious Bear

Reputation: 572

JavaScript Error: Object expected

I have an HTML page featuring a div with right-to-left scrolling text; the following JavaScript is located between the HEAD tags of the document.

function scroll(oid, iid) {
            this.oCont = document.getElementById(oid);
            this.ele = document.getElementById(iid);
            this.width = this.ele.clientWidth;
            this.n = this.oCont.clientWidth;
            this.move = function() {
                this.ele.style.left=this.n + "px"
                this.n--
                if(this.n<(-this.width)){this.n=this.oCont.clientWidth}
            }
        }
        var vScroll
        function setup() {
            vScroll = new scroll("oScroll", "scroll");
            setInterval("vScroll.move()", 20);
            }           
        onload = function(){
            setup()
        }

        $("scroll").hover(function() {
            $("scroll").stop(true, false)
        }, function(){
            scroll();
        });
        scroll();

The scrolling text works fine; however I wanted the scrolling to stop on mouse hover. Although the text does stop scrolling when the mouse cursor passes over the div, I get a javascript error "Object expected". I'm new to javascript and have no idea where I'm going wrong.

Any help would be greatly appreciated.

Upvotes: 0

Views: 954

Answers (1)

gen_Eric
gen_Eric

Reputation: 227180

Your problem is with your setInterval. You are passing it a string! This makes it use eval! That means the code is ran in global scope, so vScroll does not exist.

Instead, pass a function to setInterval:

setInterval(function(){
    vScroll.move();
}, 20);

The function passed to setInterval is called with the "context" (this value) set to null, so you cannot pass vScroll.move directly to setTimeout. You can, however. do:

setInterval(vScroll.move.bind(vScroll), 20);

but this doesn't work in all browsers.

P.S. Passing a string to setInterval is bad practice, you should always be passing a function.

Upvotes: 1

Related Questions