简体   繁体   中英

jQuery to hide next & previous buttons not working when the gallery has only one image

I have a carousel from Flickity which I'm trying to hide the left and right arrows and the pagination from.

CodePen

JQuery Code

$('.carousel').each(function() {
if ($(this).find('div.carousel-cell').length === 1) 
$(this).find('button.flickity-prev-next-button previous, button.flickity-prev-next-button next, button.flickity-page-dots').hide();
});

Carousel Code

<div class="carousel mt-1x mb-1x flickity-enabled" data-navdots="true" data-auto="false" data-buttons="true" data-wrap="true" data-adaptiveheight="false" tabindex="0">

<div class="flickity-viewport" style="height: 385.188px; touch-action: pan-y;">
    <div class="flickity-slider" style="left: 0px; transform: translateX(0%);">
        <div class="carousel-item is-selected" aria-selected="true" style="position: absolute; left: 0%;">
            <img src="/img/asset/bWFpbi9oZWFsdGhjYXJlL1BSSU1BUlkvQlVSR09QQUstQkxJU1RFUi1QUklNQVJZLTEuanBn?w=2880&amp;h=1600&amp;s=c58a408a48a295ed53498fd03655878f" alt="" title="" class="mb-1x">

        </div>
    </div>
</div>
<button class="flickity-button flickity-prev-next-button previous" type="button" disabled="" aria-label="Previous">
    <svg class="flickity-button-icon" viewBox="0 0 100 100">
        <path d="M 10,50 L 60,100 L 70,90 L 30,50  L 70,10 L 60,0 Z" class="arrow"></path>
    </svg>
</button>
<button class="flickity-button flickity-prev-next-button next" type="button" disabled="" aria-label="Next">
    <svg class="flickity-button-icon" viewBox="0 0 100 100">
        <path d="M 10,50 L 60,100 L 70,90 L 30,50  L 70,10 L 60,0 Z" class="arrow" transform="translate(100, 100) rotate(180) "></path>
    </svg>
</button>
<ol class="flickity-page-dots">
    <li class="dot is-selected" aria-label="Page dot 1" aria-current="step"></li>
</ol>

I think its happens because you run your code before the flickity create all necessary elements. Thus if you cover your code into function and call it a little bit later via setTimeout then all works fine. But in first you need to correct selector. Correct selector looks like button.flickity-prev-next-button.previous, button.flickity-prev-next-button.next, ol.flickity-page-dots instead of yours `button.flickity-prev-next-button previous, button.flickity-prev-next-button next, button.flickity-page-dots'. Finally it might be looked like

function x() {
 $('.carousel').each(function() {
   if ($(this).find('div.carousel-cell').length === 1) {
      $(this).find('button.flickity-prev-next-button.previous, button.flickity-prev-next-button.next, ol.flickity-page-dots').hide();
   }
 });
};
setTimeout(x,1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM