code-8
code-8

Reputation: 58662

How can I toggle grey-out the arrows to enhance my carousel UI experience?

I have a bunch of boxes slide-able in a carousel like this :

enter image description here

Here is the structure of my divs:

<ul>
    <li class="mp-resource"><div class="tl-box">1</div></li>
    <li class="mp-resource"><div class="tl-box">2</div></li>
    <li class="mp-resource"><div class="tl-box">3</div></li>
    <li class="mp-resource"><div class="tl-box">4</div></li>
    <li class="mp-resource"><div class="tl-box">5</div></li>
    <li class="mp-resource"><div class="tl-box">6</div></li>
</ul>

When my page load, I can't scroll to the left, so I want to grey-out my left arrow. I don't want to confuse my user.

enter image description here

In addition to that, I want to grey out my right arrow when my I can't scroll the right anymore.

enter image description here

What is the most efficient way to achieve something like that ?

How can I check to see if I am at the end of my carousel ?

Here is my live result : Fiddle

Upvotes: 0

Views: 781

Answers (1)

Pevara
Pevara

Reputation: 14310

You should detect if you are at the left or at the right after each scroll animation, and then change state of the arrow buttons accordingly. The check would be done by checking the scroll position and probably look something like this:

    function isLeft() { 
         return $scrollView.scrollLeft() == 0;   
    }
    function isRight() {
         return $overflow.width() - $carousel.width() - $scrollView.scrollLeft() <= 0;    
    }

The isLeft() function just checks if the we are scrolled entirely to the left, or the scrollLeft is 0. That one should be easy.

The isRight() basically says [width of the entire scrollable area] - [width of the part off the scrollable area that is visible] - [the amount the scrollable area is scrolled to the left]. If that becomes equal to 0 we can say we are scrolled entirely to the end. There is not much to explain here, it is basic math.

For the button state, I would use the jQuery attr function together with the 2 helper functions I just showed you, to add a disabled attribute to your buttons when required, or remove it when no longer required. Something like this:

 $leftArrow.attr('disabled', isLeft());
 $rightArrow.attr('disabled', isRight());

For the css part, you can use the attribute selector [disabled]. Something like this:

.mp-arrows[disabled] {
    cursor: not-allowed;
    color: #ccc;
    border-color: #ccc;
}

And the updated fiddle: https://jsfiddle.net/e9L60rfr/16/

Note that I also added the disabled attribute to the left button in your HTML, since on load you will always be scrolled to the left, and this way you do not need the run the checks on load.

Upvotes: 3

Related Questions