Scrollspy doesn't like hidden navigation element
Created by: AnonymousMeerkat
This is my code:
<div class="navbar-header hidden-md hidden-lg">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarthingy">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand active" href="#home">
XYZ
</a>
</div>
<div id="navbarthingy" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="hidden-xs hidden-sm"><a class="navbar-brand" href="#home">XYZ</a></li>
<li class="hidden-md hidden-lg"><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#faq">F.A.Q.</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#blog">Blog</a></li>
</ul>
</div>
It looks fine with mobile and desktop, until I add scrollspy. One that happens, when i scroll down to about, it flickers between XYZ and About constantly (in the desktop page).
The fix for this is trivial:
ScrollSpy.prototype.refresh = function () {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $el.is(':visible') // <== This is the magic line to include
&& $href.length
&& $href.is(':visible')
&& [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
After that fix, everything works fine =)