views:

212

answers:

2

How to add/show "back to top" button at bottom in a div using jquery only if height browser height is shorter than page, other wise it should be hidden?

<p><a href="#mainwrapper">Back to top</a></p>

to this

<div id="mainwrapper">

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p><a href="#mainwrapper">Back to top</a></p>

</div>

i need almost same like my this question but condition is different http://stackoverflow.com/questions/1899913/how-to-detect-linked-pdf-on-a-page-and-show-message-to-download-adobe-reader-usin/1899938#1899938

I need lightweight simple solution

+2  A: 

Something like:

var wrapper = $('#mainwrapper');
if (wrapper.outerHeight(true) > $(window).height()) {
   wrapper.append('<p><a href="#' + wrapper.attr('id') + '">Back to top</a></p>');
}
David
it's not working http://jsbin.com/enado
metal-gear-solid
no check again it's not working http://jsbin.com/iyace
metal-gear-solid
Works fine here: http://jsbin.com/afiwe
David
but it shows always
metal-gear-solid
It depends on how high your screen is :)
David
A: 

Do something like this:

$(document).ready(function(){
    showHideControl();
    $(window).resize(function(){
        showHideControl();
    });        
});

function showHideControl() {
    var h = $(window).height();
    var ch = $("#content").height();
    if (ch < h) {
        $("#backControl").hide();
    }
    else {
        $("#backControl").show();
    }
}

The html needs to be updated a little too:

<div id="mainwrapper">
<div id="content">
<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>
</div>
<p id="backControl"><a href="#mainwrapper">Back to top</a></p>
</div>
kgiannakakis
it's not working http://jsbin.com/ubowu4
metal-gear-solid
Sorry, I forgot to add the edited html. See my edited response.
kgiannakakis
no the problem is i can't add id to <p> and can't add another div. is it necessary to add another <div id="content"> and i want to add content through javascript see my linked question
metal-gear-solid