Issues with using Select2 to jump to page anchors

I have a long page organized by state. I have a Select2 element at the top of the page that I would like to use to let visitors select a state and jump to that state further down the page via an anchor.

I’ll post my code in a bit, but let me first describe the issue. My solution works in most browsers, but I’ve discovered that it fails in IE11 and Edge. In those browsers, I see the desired content location flicker briefly into view before the page gets pulled back to having the Select2 element at the top of the page. It’s like Select2 really wants to be in view.

Here is my (simplified) code:

HTML
<select class="jumpmenu">
    <option value="">Jump to a State</option>
    <option value="#alabama">Alabama</option>
    <option value="#alaska">Alaska</option>
    [ ... ]
</select>

<a name="alabama" id="alabama">&nbsp;</a>
<h2>Alabama</h2>
<a name="alaska" id="alaska">&nbsp;</a>
<h2>Alaska</h2>
[ ... ]

JQUERY
$(".jumpmenu").select2();

$('.jumpmenu').on('select2:select', function (e) {
	window.location.hash = this.options[this.selectedIndex].value;
});

Is there a better way for me to construct this jump menu so that it will jump properly in IE and Edge?

It would be really helpful if you could post your code on CodePen or a similar site. However, without actually running your code in IE or Edge, I wonder if the issue might be related to the Select2 widget closing after the selection is made, and for some reason that causes IE/Edge to reposition the viewport to the widget.

Off the top of my head, here are a few things you could try:

  1. Use setTimeout() to perform the scroll to the target anchor after some small delay (maybe even just 50 or 100 ms. would be enough).
  2. Programmatically close the Select2 widget in your event handler first, and then scroll to the target anchor.
  3. Cancel the select2:select event from within your event handler, or at least prevent it from bubbling.
  4. Use jQuery to get the top offset of the selected anchor and set $('html,body').scrollTop() to that offset, rather than setting window.location.hash. (However, this might not be desirable if you want users to be able to bookmark the scrolled page.)
1 Like

Thank you for your thoughts and suggestions. The first one worked well for me. On the off chance that someone else runs into a similar issue, here is the script I ended up using:

$('.jumpmenu').on('select2:select', function (e) {
    newHash = this.options[this.selectedIndex].value;
    setTimeout(function(){ window.location.hash = newHash;},100);
});

Once again, I appreciate the help. Have a great day!

1 Like

I’m glad it worked for you. Thanks for the Like!