Home > Mobile >  A slider through divs
A slider through divs

Time:07-12

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 >
     <div >1</div>
     <div >2</div>
     <div >3</div>
     <div >4</div>
     <div >5</div>
     <div >6</div>
     <div >7</div>
 </div>
 <a id="prev">prev</a>
 <a id="next">next</a>

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

CodePudding user response:

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 >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
</div>
<a id="prev"><button>prev</button></a>
<a id="next"><button>next</button></a>

  • Related