0

I have the following page, on the right side, there is box that should be retained at the top always, I mean, even, when we scroll down, the box should be at the top. But, I tried to achieve that through Jquery by calculating and adjusting margin-top value of the green float box [right top on the picture] and not by position:fixed

Please Note: I do not want to achieve this through CSS by using position: fixed. I want to achieve this through Jquery Stuff.

enter image description here

HTML code

<div class="mainBox">
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>
        <img src="file://D:/fonts/Grenn.jpg"/>
    </p>
    <p>Paragraph</p>
    <p>
        <img src="file://D:/fonts/Grenn.jpg"/>
    </p>
    <p>
        <img src="file://D:/fonts/Grenn.jpg"/>
    </p>
    <p>
        <img src="file://D:/fonts/Grenn.jpg"/>
    </p>
    <p>
        <img src="file://D:/fonts/Grenn.jpg"/>
    </p>
</div>

<div class="floatBox">
    <p>Sample text for floating text across pages in all the scrollbars</p>
</div>

CSS

.floatBox {
border: 2px solid green;
width: 190px;
padding: 10px;
position: relative;
float: right;
margin-top: -2300px;
}

Jquery

var boxSize = parseInt($('div.floatBox').css('margin-top'));

$(window).scroll(function() {
    var height = $(window).scrollTop();

    console.log(boxSize + 50);

    if(height < $(document).height()){
        var termp = boxSize + "px";
        console.log(termp + "temp");
        $('div.floatBox').css('margin-top', boxSize + 50 + "px");
        boxSize = parseInt($('div.floatBox').css('margin-top'));
    }
});

I'm struggling and out of notion what am I supposed to do? Any help?

User123
  • 453
  • 2
  • 6
  • 17

2 Answers2

0

Try This:

$( window ).scroll(function() {
     var height = $(window).scrollTop();
     var top = $(window).scrollTop();
    $('.floatBox').css({'margin-top': top + 'px'});
});

Here is the working fiddle for this.

Janak
  • 4,986
  • 4
  • 27
  • 45
0

Make the floatBox fixed and use top css.

.floatBox{
  position:fixed;
  top:30px;
  right:0px;
}
Diwas
  • 733
  • 6
  • 12