LittleRockStar
LittleRockStar

Reputation: 15

A slider through divs

can someone explain the code below with all functions like .ready() and .next().show().prev().hide();, .prev().show().next().hide();. And if it's possible, how can I do it JS only without JQuery? Thanks in advance.

$(document).ready(function(){
    $(".divs div").each(function(e) {
        if (e != 0)
            $(this).hide();
    });

    $("#next").click(function(){
        if ($(".divs div:visible").next().length != 0)
            $(".divs div:visible").next().show().prev().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:first").show();
        }
        return false;
    });

    $("#prev").click(function(){
        if ($(".divs div:visible").prev().length != 0)
            $(".divs div:visible").prev().show().next().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:last").show();
        }
        return false;
    });
});
<div class="divs">
     <div class="cls1">1</div>
     <div class="cls2">2</div>
     <div class="cls3">3</div>
     <div class="cls4">4</div>
     <div class="cls5">5</div>
     <div class="cls6">6</div>
     <div class="cls7">7</div>
 </div>
 <a id="prev">prev</a>
 <a id="next">next</a>

https://codepen.io/Aurelian/pen/VaBYbZ?editors=1010

Upvotes: 0

Views: 45

Answers (1)

xubeiyan
xubeiyan

Reputation: 205

those .ready() etc are jQuery methods, its give some shorthand for some JavaScrpit HTML DOM methods. you can look up this document for those methods

write the same page without jQuery, some function explains are added to code

const prevButton = document.querySelector('#prev'); // same as $('#prev')
const nextButton = document.querySelector('#next');

const cls = document.querySelectorAll('.cls'); // like $('.cls')

let showIndex = 0;

cls[showIndex].classList.add('show');

// .addEventListener('click', function () {...}) like .click(function () {...})
prevButton.addEventListener('click', () => {
  cls[showIndex].classList.remove('show');
  showIndex = (showIndex - 1 + cls.length) % cls.length; // like .prev()
  cls[showIndex].classList.add('show');
});

nextButton.addEventListener('click', () => {
  cls[showIndex].classList.remove('show');
  showIndex = (showIndex + 1) % cls.length; // like .next()
  cls[showIndex].classList.add('show');
});
.cls {
  display: none;
}

.show {
  display: block;
}
<div class="divs">
  <div class="cls">1</div>
  <div class="cls">2</div>
  <div class="cls">3</div>
  <div class="cls">4</div>
  <div class="cls">5</div>
  <div class="cls">6</div>
  <div class="cls">7</div>
</div>
<a id="prev"><button>prev</button></a>
<a id="next"><button>next</button></a>

Upvotes: 1

Related Questions