Wednesday, August 7, 2013

Floating a child element in a parent

Welcome;

In the HR Auditor product, we produce a list of chat sessions on the left side and display the results of the selected chat session on the right.  A problem we ran into was that with longer lists, the results would be hidden up at the top, forcing the user to scroll up to see the results.

We decided to "float" the results, so it would stay in view-able to the users as they scrolled up and down.  We had looked into a couple of options, but the most promising one had the issue of putting the floating object outside the parent if the results were changed.

I started to investigate what was going on and once I started looking at the code, I found it was over-complicating what we were trying to accomplish. I decided to simplify the JavaScript and write my own function.

This function will take 3 variables
 
parentElmtName This is the element that will drive the "child" element "floating".  We are using a class name, so it should be unique.
floatElmtName This is the element that will be "floating". We are using a class name, so it should be unique.
topOffset How far you want "floating" element to be from the top.
 // Keeps the child visible in the parent
 function vertFloatByClass(parentElmtName, floatElmtName, topOffset) {
    var el = document.getElementsByClassName(parentElmtName)[0];
    if(typeof el != 'undefined'){
      var parentOffset = $(el).offset().top;
      var value = parentOffset - $(window).scrollTop();

      if (0 > value) {
        var childEl = document.getElementsByClassName(floatElmtName);
        if (!$(childEl).hasClass("floatingChild")){
         var leftOffset = $(childEl).offset().left;
         $(childEl).addClass("floatingChild")
         $(".floatingChild").css({"position": "fixed", "top": topOffset + "px", 
               "left": leftOffset + "px"});
        }
     }
      else {
        var childEl = document.getElementsByClassName(floatElmtName);
        $(childEl).removeClass("floatingChild");
        $(childEl).removeAttr("style");
    }
  }
}
Our HTML looks likes this:
  <div class="parent">
    <div class="child">
      Watch me float
    </div>
  </div>
We call the function when the window is scrolled
  $(window).scroll(function () {
     vertFloatByClass("parent", "child", 20);
  });
View the code in action
Downlod Sample Code

Please feel free to let me know if you recommend any changes to the code.
Shawn Works
Email Me

No comments: