Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float a div at the bottom right corner, but not inside footer

I'm trying to implement a "go to top" button that floats at the bottom right corner of a page. I can do this with the following code, but I don't want this button to enter the footer of my page. How can I stop it from entering the footer and stay at the top of it when user scrolls the page down to the bottom of the page?

CSS

#to-top {
  position: fixed;
  bottom: 10px;
  right: 10px;
  width: 100px;
  padding: 5px;
  border: 1px solid #ccc;
  background: #f7f7f7;
  color: #333;
  text-align: center;
  cursor: pointer;
  display: none;
}

JavaScript

$(window).scroll(function() {
  if($(this).scrollTop() != 0) {
    $('#to-top').fadeIn(); 
  } else {
    $('#to-top').fadeOut();
  }
});

$('#to-top').click(function() {
  $('body,html').animate({scrollTop:0},"fast");
});

HTML

<div id="to-top">Back to Top</div>

EDIT Here is a drawing of how it should look like. The black vertical rectangle is a scroll bar. The "back to top" button should never enter the footer region. enter image description here

Here is a jsfiddle.

like image 804
CookieEater Avatar asked Oct 04 '22 03:10

CookieEater


2 Answers

The solution turned out to be more complicated than I thought. Here is my solution.

It uses this function to check if footer is visible on the screen. If it is, it positions the button with position: absolute within a div. Otherwise, it uses position: fixed.

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

$(window).scroll(function() {
    if($(this).scrollTop() == 0) {
        $('#to-top').fadeOut();
    } else if (isVisible($('footer'))) {
        $('#to-top').css('position','absolute');
    } else {
        $('#to-top').css('position','fixed');
        $('#to-top').fadeIn();
    }
});

jsfiddle

like image 92
CookieEater Avatar answered Oct 05 '22 17:10

CookieEater


Increase the value of bottom: 10px; than the height of footer. I saw your screenshot now,just add some padding-bottom to it.

like image 34
majorhavoc Avatar answered Oct 05 '22 18:10

majorhavoc