leora
leora

Reputation: 196689

Using jquery, How can I scroll to a particular div on a page is centered (vertical and horizontal)?

I have a web page that shows a seating chart (where each seat is a div). In some cases the page is very big so you might have to scroll either right or down to find your seat.

I have a link that includes a the seat name (which is the id of the div of your seat). I would like have some jquery code that "finds" and "hightlights" your seat when the page loads.

What is the best way, when a page loads, to scroll to have a certain div be at the center of the page. Once its there I can then do something like highting the div temporarily to make it stand out.

Upvotes: 1

Views: 295

Answers (1)

JSuar
JSuar

Reputation: 21091

Working Example: http://jsfiddle.net/wonq8es4/3/

The example above scrolls to a random div on the page.

// Get a random div or seat
var seat = $('#div' + randInt.toString());
// Slowly scroll to the top of the div element
$('html,body').animate({
    scrollTop: seat.offset().top-20, 
    scrollLeft: seat.offset().left-20
    },'slow');
// When the animation has completed hide, 
// change the background color, and fade in the div
$('html,body').promise().done(function(){
    seat.hide().css('background','yellow').fadeIn(1000);
});

Based on this answer: https://stackoverflow.com/a/8579673/1085891

Upvotes: 1

Related Questions