Display device color swatch number

Ive got color swatches on my product list template page that show the available colors for the product. On mobile, I want to only display the first 2 , and then provide the “more accessible” button, which jumps to a specific product page. On the desktop, I want to display the first 4 , and then provide the “more accessible” button, which will also take you to the product page.

I can display and hide the colors available on any viewport (using css), however how would I make the logic of variables when I need to provide a “more accessible” button on the desktop and mobile device?

enter image description here

HTML:

<!— Product —>
<div class="product">
 <div class="colour-swatches">
  <ul>
    <li class="swatch">Red</li>
    <l class="swatch"i>Blue</li>
    <li class="swatch">Green</li>
    <li class="swatch">Orange</li>
    <li class="swatch">Yellow</li>
    <li class="swatch">Black</li>
    <li class="swatch">Lime</li>
  </ul> 
</div>
</div>

CSS

Li.swatch {

  &:nth-child(-n+2) {
      display: block !important;
      visibility: visible !important;
  }

  @media (min-width: 600px) {

      &:nth-child(-n+3) {
          display: block !important;
          visibility: visible !important;
   }
  }
}
+4
source share
2 answers

You have all the colors available in the list, right? (even those that are not visible). If so, you can simply calculate the total number of colors available and the number of colors that you display. If all available colors are displayed, then you do not show a more accessible link, if not, then you display it.

You can use the jQuery selector :visibleto find out how many colors are currently displayed in the list (in the current viewport):

http://jsfiddle.net/cms8s720/

var all = $('ul li').length,
    visible = $('ul li:visible').length;

if(all - visible > 0) {
    $('#avail').html( (all - visible) + ' more colors available');
}
/* Simplified this for testing. This should work with your CSS */
/* Feel free to experiment with the nth-child value in here */

li:nth-child(n+3) {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product">
 <div class="colour-swatches">
  <ul>
    <li class="swatch">Red</li>
    <li class="swatch">Blue</li>
    <li class="swatch">Green</li>
    <li class="swatch">Orange</li>
    <li class="swatch">Yellow</li>
    <li class="swatch">Black</li>
    <li class="swatch">Lime</li>
  </ul> 
</div>
</div>
<span id="avail"></span>
+1

jQuery. if, . , :

if ($(window).width() <= MOBILESIZEUSED) {    

    if ($("colour-swatches > ul").length > 2){
        ...code to show more available...
    }
} else {
    if ($("colour-swatches > ul").length > 4){
        ...code to show more available...
    }
}

:

$(window).resize(functionNameHere);
functionNameHere();

, . . li ^^.

0

All Articles