Asim Zaidi
Asim Zaidi

Reputation: 28294

jquery anchor should come in the middle

I am using the following code to focus on the anchor when clicked

$('#mydiv').click(function() {
  location.href="#blah";
});

it does focus on that anchor but the issue is that part of anchor towards top of the screen. Is there a way I can kinda keep it in the middle? Thanks

Upvotes: 2

Views: 1985

Answers (2)

VictorKilo
VictorKilo

Reputation: 1870

Here's what I've done in the past:

Basically, you measure the height of the window, and the position of the div and scroll to a point which puts the div in the center of the screen.

$('#mydiv').click(function(e) {

  e.preventDefault();

  location.href="#blah";

  var windowHeight = $(window).height();
  var elementHeight = $("#blah").height();

  var elementPosition = $("#blah").position();
  var elementTop = elementPosition.top;

  var toScroll = (windowHeight / 2) - (elementHeight / 2);

  window.scroll(0,(elementTop - toScroll));
});

Upvotes: 2

sinsedrix
sinsedrix

Reputation: 4775

I think you just have to get anchor position, window size. Then you can scroll to the desired position.

        $('#mydiv').click(function (e) {
            e.preventDefault(); // to prevent default anchor behaviour
            var target_offset_top = $("#blah").offset().top;
            var window_height = document.body.clientHeight;
            $('html,body').animate({scrollTop: target_offset_top - window_height/2});
        });

Upvotes: 2

Related Questions