Theodore Steiner Theodore Steiner - 3 months ago 13
Javascript Question

Anchor tag in Drop down

I was researching how to create a drop down menu that once an option is selected, rather than jump to a new page, you scroll down the page via an anchor tag, but I can't quire figure it out.

My logic so far is to set the dropdown to a variable. Take that variable and onchange, compare it to it's current position and as long as the position isn't "0" try to make it follow the anchor link, just as if I was making it load a new page. Can someone help me with what I'm missing?

HTML:

<select name="dropDown" id="dropDown">
<option value="one"><a href="#heading1">one</a></option>
<option value="two"><a href="#heading2">two</option>
<option value="three">three</option>
</select>


<p id="heading1"><a name="heading1">Heading one</a></p>

<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br />

<p id="heading2"><a name="heading2">Heading 2</a></p>


JS:

var dropDownValue = document.getElementById("dropDown");

dropDownValue.onchange = function()
{
if(this.selectedIndex !== 0)
{
window.location.href=this.value;
}
};

Answer

You cannot put anchor tags into a <select> element. But the problem I think you are having is that you are using window.location.href when you should be using window.location.hash.

I've created this fiddle that maintains the anchor tag but uses hash. I had to update the value of "value=" to match the id where you want the browser to scroll to.

https://jsfiddle.net/jqcdyv2b/