Pradeep Nair
Pradeep Nair

Reputation: 69

Global Variable Throwing "Undefined" error in hover function

I have this global variable which is used as counter which I want to access in the jquery hover function. But some how the variable is throwing "undefined" error when I try to access it in the hover function. The code is

var i = 0

$('#ticker-area').hover(function() {
    alert(i); //THROWS UNDEFINED ERROR  
    clearTimeout(t1);   
    if (i > 0) {  
        alert(i); //NEVER REACHES HERE  
        var i = i - 1;  
        var innerText = tickerItems[i];  
        i++;  
    }  
    $('#ticker-area').html(innerText);  
}, function() {  
    clearTimeout(t1);  
    rotateTicker();  
});  

Please help. Thanks Paddy

Upvotes: 1

Views: 1443

Answers (4)

David
David

Reputation: 4110

If you are new to javascript always use http://www.jslint.com/ to check your code.

Checking your code I get the following errors:

Problem at line 1 character 10: Missing semicolon.

var i = 0

Problem at line 8 character 15: 'i' is already defined.

var i = i - 1;

Problem at line 12 character 28: 'innerText' used out of scope.

$('#ticker-area').html(innerText); 

So

  1. put a semicolon in line 1
  2. remove the var declaration in line 8
  3. put the var innerText declaration at the begining to make it visible

Upvotes: 3

Stuart Burrows
Stuart Burrows

Reputation: 10814

It is not a global variable if you usevar. When this is declared the variable is restricted to the function it is contained in. Either move the declaration into the function Or don't use the term var

edit

Take a look at this site for more info. This is the cause of the issue you are having now. Once you correct this you should take into account the suggestions in the other comments as these will become issues as well

Upvotes: 0

keegan3d
keegan3d

Reputation: 11285

Its because you are defining var i again:

var i = i - 1;

Upvotes: 1

Matt Asbury
Matt Asbury

Reputation: 5662

You need to put a ; at the end of the line var i = 0

Upvotes: 0

Related Questions