MIC MIC - 3 months ago 14
jQuery Question

Jquery prev/next navigation with show/hide content for custom calendar

I want to create some prev/next calendar solution by showing/hiding content.

I have this code for navigation (should be flexible by adding more months):

<div class="months">
<div class="082016">2016 august</div>
<div class="092016">2016 september</div>
<div class="102016">2016 october</div>
</div>


And items:

<div class="items">
<div id="082016">
<div class="item">August item</div>
<div class="item">August item</div>
<div class="item">August item</div>
</div>
<div id="092016">
<div class="item">September item</div>
<div class="item">September item</div>
<div class="item">September item</div>
</div>
<div id="102016">
<div class="item">October item</div>
<div class="item">October item</div>
<div class="item">October item</div>
</div>
</div>


What i want to achieve is to having such navigation:

august calendar item

september calendar item

October calendar item

So on arrow click it would show that month id and will change title of navigation. Also i should have no back arrow for first month and no next arrow for lats month.

Thanks in advance for any help!

Answer

My proposal for your question is a pure jQuery script:

$(function () {
  var cachedToDivs = $('.months div');

  cachedToDivs.css({'font-weight': 'bold'});
  $('.items > div').hide();
  $('.months div:lt(2)').hide();
  
  
  cachedToDivs.on('click', function(e) {
    var index = (1 + $(this).index()) % cachedToDivs.length;
    if (index == 0) {
      var txt = cachedToDivs.eq(index).text().replace(' >', '');
      cachedToDivs.eq(index).text(txt + ' >');
    } else {
      if (index == (cachedToDivs.length - 1)) {
        var txt = cachedToDivs.eq(index).text().replace('< ', '');
        cachedToDivs.eq(index).text('< ' + txt);
      } else {
        var txt = cachedToDivs.eq(index).text().replace('< ', '').replace(' >', '');
        cachedToDivs.eq(index).text('< ' + txt + ' >');
      }
    }
    cachedToDivs.eq(index).show();
    $(this).hide();
    $('.items > div').hide();
    $('.items #' + cachedToDivs.eq(index).attr('class')).show();
  }).trigger('click');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<div class="months">
    <div class="082016">2016 august</div>
    <div class="092016">2016 september</div>
    <div class="102016">2016 october</div>
</div>
<div class="items">
    <div id="082016">
        <div class="item">August item</div>
        <div class="item">August item</div>
        <div class="item">August item</div>
    </div>
    <div id="092016">
        <div class="item">September item</div>
        <div class="item">September item</div>
        <div class="item">September item</div>
    </div>
    <div id="102016">
        <div class="item">October item</div>
        <div class="item">October item</div>
        <div class="item">October item</div>
    </div>
</div>