ScienceNoob
ScienceNoob

Reputation: 231

How can i navigate to URLs with Select?

I want to navigate on an site with a select box. When a user change the select-option, it opened the url of this option.

This is my select:

<select id="navigation">
   <option value="/" selected>start</option>
   <option value="/thoughts">thoughts</option>
   <option value="/work">work</option>
   <option value="/methods">methods</option>
</select>

And this is my javascript:

document.getElementById("navigation").onchange = function() {
  var selectedOption = this.value;
  window.location.href = "http://niklasjordan.com" + selectedOption;
}

But this code doesnt work. Anybody an idea why?

Upvotes: 2

Views: 1652

Answers (2)

maxdelia
maxdelia

Reputation: 868

Assuming You're using vanilla Javascript, put your code inside this function:

var domReady = function(callback) {
    document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};

domReady(function() {
    document.getElementById("navigation").onchange = function() {
        var selectedOption = this.value;
        window.location.href = "http://niklasjordan.com" + selectedOption;
    }
});

(This only works on IE9 and above)

Short explanation: You have to wait your DOM fully loaded before manipulation it!

Upvotes: 3

ScienceNoob
ScienceNoob

Reputation: 231

Thanks for your help, guys!

The solution was very simple: i put my code from the head before the closed body tag. Voilá! It run...

Upvotes: 1

Related Questions