JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrap">
<h4>Wrap</h4>
<div class="v-spacer" style="float: right">
</div>
<div id='dynamicContent' style="background:black; color: white; padding: 10px;">
Dynamic Content
<div style="display: none;">
Hovered!
</div>
</div>
...
<div>
<button type="button" id="thingToggle" style="display: block;">
Toggle
</button>
</div>
<div class="thing">
<h4>Thing</h4>
</div>
...
</div>
<div class="v-spacer">
</div>
CSS
.v-spacer {
height: 400px;
width: 10px;
background: green;
border: 1px dotted black;
}
.wrap{
height: 200px;
background: white;
overflow: hidden
;
position: relative;
border: 3px dashed black;
}
.thing {
height: 300px;
width: 50px;
background: #882233;
position: fixed;
top: auto;
left: auto;
}
JavaScript
function scrollFixed() {
$('.thing').each(function() {
var $w = $(window);
var $thing = $(this);
var sl = $w.scrollLeft();
var st = $w.scrollTop();
$thing.parents().not('html,body').each(function(i, p) {
var $parent = $(p);
sl += $parent.scrollLeft();
st += $parent.scrollTop();
console.log(sl, st);
});
$thing.css({
"margin-top": (-st) + "px",
"margin-left": (-sl) + "px"
});
});
}
function bindScrollFixedEvents() {
// Most important, bind to the Window's scroll and resize event
$(window)
.unbind('.scrollFixed')
.on('scroll.scrollFixed, resize.scrollFixed', scrollFixed);
// Find all parent elemetns of .thing and bind scroll event
$('.thing').parents()
.unbind('.scrollFixed')
.on('scroll.scrollFixed', scrollFixed);
}
bindScrollFixedEvents();
// A little extra to show use-cases:
$('#thingToggle').on('click', function() {
$('.thing').toggle();
});
$('#dynamicContent')
.on('mouseover', function() {
$(this).children().show();
})
.on('mouseout', function() {
$(this).children().hide();
})
;