Search code examples
javascriptjquerycsssettimeoutsticky

jQuery Sticky Plugin Variable Top Spacing


I'm using the jQuery sticky plugin to stick the menu and contact information to the top. The site is responsive, so spacing from the top for the menu changes. I'm trying to do different spacing based on the CSS value of the contact info, but it's not working. I was pretty sure my jQuery was correct...

 $(document).ready(function(){   
 function checkForFloat()
  {
    setTimeout(checkForFloat, 100);
    if($("#contact").css("float") === "none") {
      $("#headerbg2").sticky({topSpacing:180});   
    }
    else if (!$("#contact").css("float") === "none") {
      $("#headerbg2").sticky({topSpacing:120});
    }
  }
});

http://jsfiddle.net/1j9cdsro/


Solution

  • To make Dynamic changes to the sticky from the documentation it needs to unstick first and updated

    $("#headerbg2").unstick() &  $("#headerbg2").sticky('update')
    

    this also needs to change (!$("#contact").css("float") === "none") to either ($("#contact").css("float") != "none") or else { .. }

    Demo with dynamic window resize

    http://jsfiddle.net/w2jv7szg/

    Code

          $(document).ready(function () {
          $("#headerbg1").sticky({
              topSpacing: 0
          });
    
          function checkForFloat() {
    
    
              if ($("#contact").css("float") === "none") {
                  $("#headerbg2").sticky({
                      topSpacing: 50
                  });
              } else {
                  $("#headerbg2").sticky({
                      topSpacing: 120
                  });
              }
          }
          setTimeout(checkForFloat, 1000);
    
    
          window.addEventListener('resize', function (event) {
                $("#headerbg2").unstick()
    
              if ($("#contact").css("float") === "none") {
                  $("#headerbg2").sticky({
                      topSpacing: 50
                  });
                  $("#headerbg2").sticky('update')
              } else {
                  $("#headerbg2").sticky({
                      topSpacing: 120
                  });
                  $("#headerbg2").sticky('update')
              }
          })
    
      });