10

We all know that scroll to top with named anchors via HTML is possible but is it possible to scroll to the top when another HTML element is clicked that is not surrounded by tags? For instance, a DIV?

EDIT: Apologies all, I did not see this was a duplicate question. I did a search and didn't find anything.

cela
  • 2,059
  • 3
  • 19
  • 37
Aaron Brewer
  • 3,363
  • 17
  • 45
  • 73

7 Answers7

23
$('div').on("click",function(){
      $(window).scrollTop(0);
});

You can insert every kind of html tag into the bracket's

mas-designs
  • 7,160
  • 1
  • 27
  • 53
9

Yes, you might want to do it with Javascript by using

window.scrollTo(0, 0);

and assigning it to the div

<div onclick="window.scrollTo(0, 0);">Element</div>
ianaz
  • 2,315
  • 1
  • 25
  • 34
6

if you want to go for jquery solution than you can use

$(document).ready(function() {

    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });

});

html will be

<a name="top"></a>
...
<a href="#top">Back to top</a>

full article : Scroll to the top of a webpage with jQuery

Pranay Rana
  • 164,177
  • 33
  • 228
  • 256
4

You can achieve this by using JavaScript:

$("#my-div").on("click", function() {
    window.scroll(0,0);
});

or with jQuery:

$("#my-div").on("click", function() {
    $(window).scrollTop(0);
});
cela
  • 2,059
  • 3
  • 19
  • 37
Tobias Krogh
  • 3,340
  • 17
  • 14
4

this should work for any block element:

$('#element_id').click(function(){
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
});

good luck ...

airyt
  • 344
  • 2
  • 9
1

Yes it is possible, you should add event onclick to that element and use .scrollTop()

for more info see scrollTop

Anton Baksheiev
  • 2,151
  • 2
  • 12
  • 14
1

You could listen for a click event on your div and use scrollTo when it is clicked.

window.scrollTo( x-coord, y-coord ):

Scrolls to a particular set of coordinates in the document.

x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.

Community
  • 1
  • 1
Chase
  • 26,531
  • 1
  • 45
  • 45