3

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;
}
};
Theodore Steiner
  • 1,553
  • 2
  • 23
  • 34

3 Answers3

3

Here is a simple example.

P.S: Avoid anchor inside option.

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

dropDownValue.onchange = function() {
  if (this.selectedIndex !== 0) {
    window.location.href = this.value;
  }
};
p {
  min-height: 500px;
}
<select name="dropDown" id="dropDown">
  <option value="#heading1">one</option>
  <option value="#heading2">two</option>
  <option value="#heading3">three</option>
</select>

<p id="heading1"><a name="heading1">Heading one</a>
</p>
<p id="heading2"><a name="heading2">Heading two</a>
</p>
<p id="heading3"><a name="heading3">Heading three</a> 
Pugazh
  • 9,453
  • 5
  • 33
  • 54
2

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/

adam-beck
  • 5,659
  • 5
  • 20
  • 34
0

I have some suggestion.

Method 1: You can use dropdown navigation

https://getbootstrap.com/docs/5.1/components/dropdowns/

Method 2: You can also use select2.js

https://select2.org/