user2252219
user2252219

Reputation: 865

How to adjust page to scroll to center on clicking on carousel?

I'm trying to get it so that when you click on the carousel, the page will adjust to have the carousel in the center. This website (http://studionewwork.com/) shows this when you click on their carousel. I'm still learning about Jquery so I'm not yet adept at commands yet.

http://jsfiddle.net/8bJUc/614/

$(document).ready(function () {
    $("#owl-demo").owlCarousel({
        navigation: true,
        pagination: true,
        lazyLoad: true
    });
});


$('.owl-demo').on('click', function(e) { 
  var el = $( e.target.getAttribute('href') );
  var elOffset = el.offset().top;
  var elHeight = el.height();
  var windowHeight = $(window).height();
  var offset;

  if (elHeight < windowHeight) {
    offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
  }
  else {
    offset = elOffset;
  }
  var speed = 700;
  $('html, body').animate({scrollTop:offset}, speed);
});

Upvotes: 2

Views: 261

Answers (1)

posixpascal
posixpascal

Reputation: 3140

Hey I updated your fiddle to make it work: http://jsfiddle.net/8bJUc/649/

Basically you are using $(".owl-demo") as if it's a class, but it's an ID. Then the onClick function tries to get the clicked element but fails doing so.

var el = $( e.target.getAttribute('href') );

This line basically says:

Get the href-attribute from the clicked element and use jQuery to locate any elements matching the href attribute. I removed this since you don't specify the href attribute anywhere.

$('.owl-carousel').on('click', function(e) { 

  var el = $(".lazyOwl", this);
  var elOffset = el.offset().top;
  var elHeight = el.height();
  var windowHeight = $(window).height();
  var offset;

  if (elHeight < windowHeight) {
    offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
  }
  else {
    offset = elOffset;
  }
  var speed = 700;
  $('html, body').animate({scrollTop:offset}, speed);
});

Please note that the example carousel you posted doesn't work as expected on my Macbook Air 11''. The carousel jumps around whenever I click on it.

Upvotes: 2

Related Questions