0

I need a 'Page section' to stick in place for (x) amount of scrolling and then move onto the next section. I've tried putting them into the child theme but nothing... Can someone tell me a good way to do wthis that's not Javascript heavy?

CSS

.isSticky {
  top: 0;
  position: fixed;
}

HTML

<div>
  <section id="top"></section>
  <section id="test2"></section>
  <section id="bottom"></section>
</div>

JS

$(document).ready(function () {
  var el = $('#test2');
  var elTop = el.position().top;
  $(window).scroll(function () {
    var windowTop = $(window).scrollTop();

    if (windowTop >= elTop) {
      el.addClass('isSticky');
    } else {
      el.removeClass('isSticky');
    }
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
  • There a few closing brackets and parenthesis missing. Is that on purpose? – blurfus Jan 15 '15 at 20:21
  • I must have not pasted it correctly, I went to codepen and used the same functioning code they were using for what I needed.. so no not on purpose. but I'm not very great with code as you can see, just learning. – Tisha Rodriguez Jan 15 '15 at 20:26
  • no worries. Do you mind editing your question then and adding the missing bits? – blurfus Jan 15 '15 at 20:29
  • What if the user scrolls back up? What if the user's device is not tall enough to show the element? What if the user's screen is so large they can see the whole page and can't scroll? What if the user jumps directly to an anchor tag? You have to think about all these things. – Code Whisperer Jan 15 '15 at 20:33

1 Answers1

3

This answer might not be 100% pragmatic, due to current lack of support, but soon you will be able to use the position: sticky property of CSS, currently supported in Firefox and prefixed in Safari/iOS (Caniuse).

The feature was previously enabled in Chrome, but then subsequently removed in the interest of re-doing it more efficiently.

html, body {
    margin: 0;
}

body * {
    margin: 20px;
    padding: 20px;
}

.header {
    margin: 0;
    padding: 20px;
    background: #000;
}

.header span {
    display: block;
    color: #fff;
    margin: 0 auto;
    text-align: center;
    padding: 0;
}

.placeholder {
    border: 1px solid black;
    margin: 0 auto;
    text-align: center;
    height: 300px;
}

.slider {
    background: #006264;
    color: white;
    font-weight: bold;
    margin: 0 auto;
    position: sticky;
    top: 0px;
}
<div class="header"><span>This is a header</span></div>
<div class="placeholder">This div holds place</div>
<div class="slider">This should slide up and then stick.</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>
Community
  • 1
  • 1
TylerH
  • 20,799
  • 66
  • 75
  • 101