Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="wrap">
  <div class="content">
    <h1>I saw this sweet highlighting trick and you won't believe what happened next...</h1>
    
    <div class="full-width">
      <img src="//placekitten.com/1280/640">
    </div>

    <p class="i-can-has-a-colored-thing">
      This is an implementation of a nice animated highlighting effect as it can be seen on the <a class="highlight" href="https://projectbloks.withgoogle.com/">project bloks website</a>. Only difference is that it's done here with all fancy <span class="highlight">css-variables and using <tt>mix-blend-mode</tt></span> to even make it work with different background-colors.
    </p>
    
    <p>
      It uses <em><span class="highlight">100% organic Javascript</span> (pure ES6, no library-sugar)</em> that makes it easy to integrate into almost every regular website (sorry react-users, but you can just as easily use the css and let react do the rest...)
    </p>
    
    <p>
      A note on Browser-support: <em class="highlight">CSS-Variables are a thing now, and it's just awesome!!</em> (well at least for Firefox, Chrome and Safari, Edge will probably follow soon. Do we still talk about IE these days?). The same goes for ES6-support (unless your browser is Safari), which is why I didn't enable babel for the JS-Code (again, if your browser is Safari, you might want to do this now to see the effect).
    </p>
    <p>
      <em class="highlight">And what if CSS-Variables are not supported?</em>
      Good question. For these cases there exists a <a class="highlight" href="https://github.com/MadLittleMods/postcss-css-variables">post-css plugin</a> that seems to do a decent job of at least creating a good static fallback (in this case the scroll-effect doesn't work, or the JS would need to generate the whole grandient-definition instead of just updating a variable and where's the fun in that, right?).
    </p>
    
    <div class="full-width">
      <img src="//placekitten.com/1920/600">
    </div>
    
    <h2><span class="highlight">Whoa. Look how awesome this is!!</span></h2>
    <p>
      Although it is to say, that it <span class="highlight">only works across multiple lines with <tt>inline</tt> elements</span> which is why the headline above needs to contain a <tt>&lt;span class="highlight"&gt;</tt>. Oh and heres some blind-text that is just there because I can't be bothered to fix the last remaining edge-cases:
    </p>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.   
      Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.   
    </p>
  </div>
</div>
              
            
!

CSS

              
                /* ---- here's the fun-stuff */
:root {
  --highlight-vstart: 0.4em;
  --highlight-vend: 0.9em;
  --highlight-color: yellow;
  --highlight-range: 100%;
}

.highlight {
  mix-blend-mode: multiply;
  background: 
    linear-gradient(to bottom,
      white, 
      white var(--highlight-vstart), 
      transparent var(--highlight-vstart), 
      transparent var(--highlight-vend), 
      white var(--highlight-vend), 
      white),
    
    linear-gradient(to right,
      var(--highlight-color), 
      var(--highlight-color) var(--highlight-range), 
      white var(--highlight-range), 
      white)
  ;
}


/* ---- boring css here... */
body {
  font-size: 26px;
  line-height: 1.5;
}
h1, h2 { margin: 2em 0 1em; font-family: sans-serif; font-weight: 100; color: #666; letter-spacing: -0.02em; }
h1 { font-size: 4rem; line-height: 1.1; margin: 2em 0; }
tt { font-size: 0.75em; }

.i-can-has-a-colored-thing { position: relative; }
.i-can-has-a-colored-thing:after {
  content: '';
  display: block;
  position: absolute; bottom: 0; right: 0;
  width: 400px; height: 200px; z-index: -1;
  pointer-events: none;
  background-color: rgba(140, 180, 200, 0.2);
  transform: rotate(20deg) translate(-50%, 20%)
}

@media (min-width: 768px) {
  .content { width: 768px; margin: 0 auto; }
  
  .full-width { 
    position: relative;
    left: calc(-50vw + 768px / 2);
    width: 100vw;
  }
}

.full-width img { width: 100%; }
              
            
!

JS

              
                // ---- boring utility-functions first

// used to defer handling of scroll-events to the next 
// animation-frame without risking to run the code multiple
// times if the event fires multiple times during a frame
const debouncedRAF = (function() {
  let frameId = null;

  return fn => ev => {
    if (frameId !== null) { return; }
    
    frameId = requestAnimationFrame(time => {
      fn(time);
      frameId = null;
    });
  };
}) ();

// regular debounce-function. `fn` will be called by the 
// returned function  after it has not been called for
// `time` milliseconds.
function debounce(fn, time) {
  let timerId = null;

  return (...args) => {
    if (timerId) {
      clearTimeout(timerId);
    }

    timerId = setTimeout(() => fn(...args), time);
  }
}

// get the page-relative offsetTop of an element
function getPageOffsetTop(el) {
  let offset = 0, node = el;

  do {
    offset += node.offsetTop;
  } while(node = node.offsetParent);

  return offset;
}



// ---- now the interesting part

// creates a scroll-highlighter for the specified list of elements.
//
// Usage:
// 
//     const highlighter = scrollHighlighter(elements);
//
//     // if you need to add elements later, use this:
//     highlighter.elements.push(newElements);
//
//     // call this from a scroll-event or animation-frame 
//     // with the scroll-position (updates css-variables of elements):
//     highlighter.update(scrollTop);
//
//     // finally, make sure to update cached positions if 
//     // page-geometry changes (eg. window.onresize):
//     highlighter.reflow();
//
// And thats it.
function scrollHighlighter(elements) {
  const START_OFFSET = 0.3;
  const END_OFFSET = 0.7;

  // cache for page-relative offsetTop per element
  const offsets = new WeakMap();
  
  const instance = {
    // the elements handled by this instance. 
    // Feel free to add more elements after creation 
    elements: Array.from(elements),

    // update all elements with a new scroll-position, should be 
    // called from the scroll-event.
    // highlighting of an element will begin when the element 
    // is 30% within the viewport and should end when it's at 70%
    // (measured from bottom to top)
    update(scrollTop) {
      const endAt = END_OFFSET;
      
      this.elements.forEach(el => {
        const elOffset = offsets.get(el);
        const relPosition = 1 - (elOffset - scrollTop) / this.windowHeight;

        // readjust startAt to a certain extent if the element 
        // would normally be partly highlighted at page-load
        let startAt = START_OFFSET;
        const startOffset = this.windowHeight * (1 - startAt);
        if (startOffset > elOffset) {
          startAt = Math.min(endAt, 1 - elOffset/this.windowHeight);
        }
        
        const progress = (relPosition - startAt) / (endAt - startAt);
        const clampedProgress = Math.min(1, Math.max(0, progress));
        
        // i love this so much...
        el.style.setProperty(
            '--highlight-range', 
            (clampedProgress * 100).toFixed(0) + '%'
        );
      });
    },

    // prevent sync reflows by caching the top-offsets 
    // for all elements.
    // must be called whenever the list of elements or 
    // their position on the page changes (best bet:
    // window.resize)
    reflow() {
      this.windowHeight = window.innerHeight;      
      this.elements.forEach(el => {
        offsets.set(el, getPageOffsetTop(el));
      });
    }
  };
  
  // make .elements.push work properly
  instance.elements.push = (...args) => {
    const result = Array.prototype.push.call(instance.elements, ...args);
    instance.reflow();

    return result;
  }
  
  // initialize
  instance.reflow();
  instance.update(0); 
  
  return instance;
}


// finally: create the highlighter and bind events
const hl = scrollHighlighter(document.querySelectorAll('.highlight'));

window.addEventListener('resize', debounce(() => hl.reflow(), 100));
document.addEventListener('scroll', debouncedRAF(() => {
  hl.update(window.pageYOffset || document.documentElement.scrollTop);
}));
                                                 


              
            
!
999px

Console