Manipulating HTML based on viewport position with jQuery

Manipulating HTML based on viewport position with jQuery

Created:29 Jun 2017 15:16:14 , in  Web development

At times, it is desirable to be able to manipulate a HTML element styling and/or behavior on the basis of its current proximity, presence or absence in the viewport .

The viewport is user's visible area of a web page on the screen. However, that is just the tip of the iceberg. A sort of custom viewport for a HTML document fragment can be also created easily with a block element ( div or section etc. ).

Digging an inch deeper, in the default case, window is the containing element for all the content.

As for the custom viewports, the containing element should have at least its overflow CSS property set to "scroll-y" (for vertical scrolling) . Also, its height dimension should be set to some fairly small length or percent of its parent element to force vertical scroll bar.

For the purposes of this article, I'm interested equally in both sorts of vieports.

Done with the basics on the viewports, we can move on to a real life scenario.

Here is a simple one.

Imagine, you need to toggle opacity for a HTML element(s) based on whether the element is in the viewport or off it.

Manipulating HTML opacity based on location relative to the viewport

For scenarios like the one described above I wrote viewportFadeInOut. ViewportFadeInOut is a tiny jQuery plugin. It uses Mudit's Ameta isInViewport. IsInViewport is freely available jQuery plugin available from github.com.

Here is viewportFadeInOut:


/**
 * Plugin : viewportFadeInOut (jQuery)
 * Description : animate HTML element opacity as it enters / leaves the viewport 
 * Author : Sylwester Wojnowski
 * WWW : wojnowski.net.pl
 */

$.fn.viewportFadeInOut = function(opts) {
  var defs = {
    container : null,
    container_height:'200px',
    tolerance : 0,
    timeFadeIn : 500,
    fadeInTo : 0.95,
    timeFadeOut : 500,
    fadeOutTo : 0.25,
    interval : 2000,
    easing:'linear',
    onCompleteIn : null,
    onCompleteOut : null
  }
      
  var opts = $.extend({}, defs, opts);
  var elms = $(this);
  if ( opts.container != null ) {
    $(opts.container).css({
      'height':opts.container_height,
      'overflow-y':'scroll'
    });
  }
    
  setInterval(function(){
    elms.each(function(index,elm){
      var elm = $(elm);
      var tol = parseInt(opts.tolerance);
      var psel = ':in-viewport('+tol+')';
            
      tol = ( tol == null || tol < 0) ? 0 : tol ;
            
      if ( opts.container != null ) {
        psel = ':in-viewport(' +tol+ ',' +opts.container+ ')'; 
      }     
            
      if( elm.is(psel) ){
        elm.fadeTo(opts.timeFadeIn,opts.fadeInTo,opts.easing,opts.onCompleteIn);
      }else{
        elm.fadeTo(opts.timeFadeOut,opts.fadeOutTo,opts.easing,opts.onCompleteOut);
      }
    })
  },opts.interval);
};

Installing viewportFadeInOut

Add jQuery library, isInViewport.min.js to the head section of your HTML document. isInViewport project is available here

Save the above code in viewportFadeInOut.js and also add it to the head section of your HTML document.


<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.2.min.js"></script>
<script type="text/javascript" src="isInViewport.min.js"></script>
<script type="text/javascript" src="viewportFadeInOut.js"></script>

Add one of the initialization scripts below to the head of your HTML document.

Configuring viewportFadeInOut

ViewportFadeInOut accepts several configuration options:

container - selector - selector for element to turn into a viewport, if null (default), window will be used

container_height - string - viewport element heigh, defaults to '200px'

tolerance - int - tolerance in distance between the viewport and element, defaults to 0

timeFadeIn - int - speed of fadeIn animation in milliseconds, dafaults to 500

fadeInTo - int/double - final opacity level for element in viewport, in range of 0 and 1, defaults to 0.95

timeFadeOut - int - speed of fadeOut animation in milliseconds, dafaults to 500

fadeOutTo - int/double - final opacity level for element in viewport, in range from 0 to 1, defaults to 0.25

interval - int - interval in milliseconds before animating function for elements in the viewport and off it is applied, defaults to 2000

easing - animation easing type, defaults to 'linear'

onCompleteIn - function - callback used after animation for elements currently in the viewport has completed, defaults to null

onCompleteOut - function - callback used after animation for elements currently off the viewport has completed, defaults to null

Manipulating HTML with window as the viewport

If container option for viewportFadeInOut is null, window will be used as the viewport. The code animates opacity of all sections as they enter / leave the viewport.


(function ($) {
  $(document).ready(function(){
    $("section").viewportFadeInOut();
  })
})(jQuery);

Manipulating HTML using a custom block element as the viewport

In the fragment of code below element with id 'customViewport' becomes the viewport. ViewportFadeInOut animates opacity of a group of paragraphs as they enter / leave the containing block.

In this example some extra configuration options have been set to custom values and callbacks added.


(function ($) {
  $(document).ready(function(){
    $("p","#customViewport").viewportFadeInOut({
      container:'#customViewport',
      container_height:'100px',
      interval : 2000,
      fadeOutTo:0.2,
      // callback to execute after fadeIn has completed
      onCompleteIn : function(){
        $(this).css('background','#ddd')
      },
      // callback to execute after fadeOut has completed
      onCompleteOut : function(el){
        $(this).css('background','#fff')
      }
    }); 
  })
})(jQuery);
And here is a working example using the above initialization code.

Donec non libero eu justo euismod pharetra. Quisque orci ante, ullamcorper at pellentesque non, tempor eget dolor. Aliquam mollis laoreet lacus id bibendum. Etiam magna ligula, facilisis sed lacinia eget, sagittis quis mauris. Donec nisi magna, tempor vel tincidunt nec, pretium at erat.

Fusce at placerat urna. Ut metus dui, volutpat eu egestas quis, lacinia ac ex. Ut maximus, mi sit amet posuere interdum, metus est placerat mi, eleifend porta metus nisl at sapien. Donec tempus magna a enim vehicula, ac tristique odio tristique. Vestibulum ut est velit. Maecenas placerat mattis purus. Phasellus tristique ipsum sit amet pellentesque consequat.

Curabitur ligula purus, scelerisque nec ultrices ac, consequat quis felis. Duis cursus sapien ut augue viverra iaculis. Nam nec ligula sit amet elit bibendum lacinia. Nam iaculis sem ligula, sit amet ornare justo mattis ac. Mauris venenatis malesuada erat, et finibus turpis elementum eu. Etiam velit magna, commodo et leo ac, ornare faucibus nisl.

Phasellus feugiat tortor interdum leo condimentum volutpat. Integer id turpis neque. Nulla quis cursus urna, ut luctus nunc. Suspendisse a ornare nunc, sit amet porttitor nibh. Pellentesque sapien dui, euismod ornare vehicula non, posuere vitae sem. Fusce in mi erat.

Quisque porta efficitur nulla a blandit. Vivamus at volutpat nisl. Donec bibendum nibh sit amet sem venenatis dictum. Cras mattis massa id ante suscipit, ac venenatis nibh molestie. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Interdum et malesuada fames ac ante ipsum primis in faucibus.

Praesent et nisl sodales, pretium mauris vitae, gravida est. Nullam velit lorem, auctor at enim id, malesuada aliquet massa. Vivamus dapibus euismod libero, sit amet euismod turpis vestibulum a.

Final thoughts

The example in this article focuses on manipulating opacity of a group of HTML elements as they enter, remain in, or leave the viewport. However, the idea and the solution presented here are fairly general. They can be applied to many other similar problems involving the viewport.

I hope you have found the article interesting and informative.

This post was updated on 30 Jun 2017 23:02:04

Tags:  JavaScript ,  jQuery 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.

Copyrights

©Copyright, 2017 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. " Manipulating HTML based on viewport position with jQuery." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/manipulating-html-based-on-viewport-position-with-jquery