1
\$\begingroup\$

I have a carousel (Owl Carousel) with vertically centered controls. Because of the structure, I have to absolutely position the previous and next arrow. Because the page is responsive, their position is dynamic. The size of the controls may also change.

My carousel.

I've written a function that runs on load and resize. It gets the height of the image and the height of the controls, subtracts the latter from the former, divides by two, and then uses that number as the controls' margin-top.

It works, but I'm questioning if I'm getting and using all the variables correctly. Does JavaScript read in order? Where it runs the first line, then the next, then the next... I'm strong in CSS but JS has always been a crutch.

Can I write this more efficiently?

function centerCarouselControls() {
  var carouselImage = $('.carousel-card > img');
  var carouselControls = $('.owl-nav > div');
  var carouselHeight = carouselImage.outerHeight();
  var controlHeight = carouselControls.outerHeight();
  var controlMargin = (carouselHeight - controlHeight) / 2;
  carouselControls.css('margin-top', controlMargin);
}

$('.carousel-card > img').load(centerCarouselControls);
$(window).on('resize', centerCarouselControls + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Is it not possible to wrap both the 'arrow' and the image inside a relative div then do some absolute position and stuff?

jsfiddle so you can change the height to see it change without javascript: https://jsfiddle.net/3bm2hp5f/1/

Code:

html, body {
  height: 100%;
  width: 100%
}
<div id="resizable" style="width: 30%; height: 50%; resize: both; position: relative; display:inline-block; border: 3px solid black">
  <div style="position: absolute; top: 50%; transform: translateY(-50%);">
    &lt;
  </div>
  <image style="width: 100%; height: 100%;"></image>
</div>
<div style="display: inline-block">
 something else
</div>

\$\endgroup\$
1
  • \$\begingroup\$ No, I can't change the structure of the container(s). I'm using Owl Carousel and the navigation is created when the plugin initializes. The nav div is a sibling of the div that wraps the image and caption. Besides that, the images are lazy loaded and have an initial height of zero. I'm pretty good at CSS and had no solutions via that route. \$\endgroup\$
    – kburgie
    Commented Mar 1, 2017 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.