Stefan Gum
Stefan Gum

Reputation: 67

Why i get a error - indexOf Uncaught TypeError

What's the Problem? Why it cannot find the function indexOf and length?

window.onpopstate = function(event) {
    var string1 = document.location;
    var stringpos;
    stringpos = string1.indexOf('#');

    var hashstring = string1.substring(stringpos,string1.length());

    alert(hashstring);

    alert("location: " + document.location);
};

Upvotes: 0

Views: 233

Answers (3)

dezhik
dezhik

Reputation: 1030

First of all use

var string1 = document.location.href

or

var string1 = document.location.toString()

then use string1.length instead of string1.length() which throws Uncaught TypeError: string1.length is not a function

Upvotes: 0

Victory
Victory

Reputation: 5890

Try getting the hash directly instead of with string manipulation.

    window.onpopstate = function(event) {
        var hashstring = document.location.hash;
        alert(hashstring);
        alert("location: " + document.location);
    };

Upvotes: 0

Oriol
Oriol

Reputation: 288100

document.location is an object which does not have the indexOf method. In general, only expect strings and arrays to have that method (and document.location is neither of those).

I think you wanted to use indexOf on document.location.href, which is a string:

document.location.href.indexOf('#');

Upvotes: 2

Related Questions