Search code examples
javascriptjquerycountcountingfigure

Count elements and show/update value of current in view + total


I am trying to understand how to count and display current and total number of figures on my page.

My html

<div class="is-vertical">
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
</div>

My js attempt of trying to get the total number

var totalItems = $( ".is-vertical figure" ).length;
    

My js attempt of trying to display the variable in an appended span


$('.is-vertical').append('<span class="numbers">')+totalItems.join('</span>');
    
});

For the last part of showing the current one I am wondering if one could use ($(window).scrollTop() somehow and update the value of the current figure in view.


Solution

  • It ended up solved by this script:

    var $isVertical = $('.is-vertical'); // <div class="is-vertical">
    var $numbersSpan = $('<span>', { class: 'numbers', text: 'Figure 1 of ' + $isVertical.find('figure').length });
    $isVertical.prepend($numbersSpan);
    
    // Function to update the current figure number
    function updateCurrentFigureNumber() {
      var windowHeight = $(window).height();
      var scrollTop = $isVertical.scrollTop();
      var figureHeight = $isVertical.find('figure').height();
      
      // Calculate the current figure number in view
      var currentFigureNumber = Math.floor((scrollTop + windowHeight * 0.75) / figureHeight) + 1;
      
      // Update the text inside the 'numbers' span
      $numbersSpan.text( + currentFigureNumber + ' / ' + $isVertical.find('figure').length);
    }
    
    // Add an event listener to update the current figure number when scrolling
    $isVertical.scroll(updateCurrentFigureNumber);
    
    // Call the updateCurrentFigureNumber function initially to set the correct figure number
    updateCurrentFigureNumber();