GPinskiy
GPinskiy

Reputation: 307

Unexpected Token Function using JQuery

I have a function that I have set on an interval:

function refresh() {
    if ($("#autorefresh").checked) {
        var elem = $("#messagesDiv");
        elem.scrollTop = elem.scrollHeight;
    }
}

var autoRefresh = window.setInterval(refresh(), 1000);

and a simple checkbox input on the html page. I continue to get an Unexpected Token Function on the refresh() function. I already checked for too many commas, too many parentheses, there doesn't seem like anythings wrong in that sense. Any Ideas?

Upvotes: 0

Views: 2900

Answers (1)

epascarello
epascarello

Reputation: 207501

var autoRefresh = window.setInterval(refresh(), 1000);

needs to be

var autoRefresh = window.setInterval(refresh, 1000);

and you will find out that

$("#autorefresh").checked

needs to be

$("#autorefresh").prop("checked")

and your third problem, there is no scrollTop and scrollHeight properties either, you are NOT working with a DOM element

elem.scrollTop = elem.scrollHeight;

should be something like

elem.scrollTop(elem[0].scrollHeight);  

The updated code would be

function refresh () {
    if ($("#autorefresh").prop("checked")) {
        var elem = $("#messagesDiv");
        elem.scrollTop(elem[0].scrollHeight);
    }
}
var autoRefresh = window.setInterval(refresh, 1000);

Running example:

http://jsfiddle.net/7eEcw/

Upvotes: 3

Related Questions