0

I'm new to javascript thing and got the below slider javascript and html code from online.

<script>
    var slideIndex = 1;
    showSlides(slideIndex);
    
    function blogcurrentSlide(n) {
      showSlides(slideIndex = n);
    }
    
    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("blogdot");
      if (n > slides.length) {slideIndex = 1}    
      if (n < 1) {slideIndex = slides.length}
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";  
      }
      for (i = 0; i < dots.length; i++) {
          dots[i].className = dots[i].className.replace(" blogactive", "");
      }
      slides[slideIndex-1].style.display = "block";  
      dots[slideIndex-1].className += " blogactive";
    }
</script>


<span class="blogdot" onclick="blogcurrentSlide(1)"></span>
  <span class="blogdot" onclick="blogcurrentSlide(2)"></span>
  <span class="blogdot" onclick="blogcurrentSlide(3)"></span>

<div class="mySlides fade">
  <% @loadpostslandingfirst.each do |post| %>
</div>
<p id="blogtitle">
  <b>
    <%= truncate(post.blog_title, :length=>60) %>
  </b>
</p>

Currently, it works on click only but I also want the swipe function on the smartphone.

Slider with touch function

I found a similar article but couldn't understand it at all.

Any help would be much appreciated.

carrey
  • 109
  • 1
  • 8
  • How did you implement the `click` handler? Inline? – hungerstar Jul 23 '20 at 20:51
  • @hungerstar If you are talking about html code, I updated my question – carrey Jul 23 '20 at 20:54
  • Could you elaborate on what parts of the accepted answer in that question you didn't understand? https://stackoverflow.com/a/46849125/119549 – Jacob Jul 23 '20 at 20:58
  • @Jacob I couldn't understand how the code `var slider = document.getElementsByClassName('slider')[0];` is related to the main functions. `function slideLeft()` and `function slideRight()`. Also, I couldn't have any idea of how to apply this into my codes. – carrey Jul 23 '20 at 21:02
  • @carrey that accepted answer uses event handlers bound to a DOM element, your code example registers event handlers via an `on` attribute. `on` attribute are discouraged. They are more difficult to maintain and less flexible than event handlers bound to a DOM element. You will need to bind a `click`, `touchstart`, and `touchmove` handlers to your slide elements. If you follow the "answer" link in the accepted answer, you'll see how to create DOM handlers. The code you posted above will need to keep track of the index of the slide that is to be displayed and passed to `showSlides`. – hungerstar Jul 24 '20 at 11:50

1 Answers1

0

Not entirely sure what you are after, but I think you are looking for something like this.

https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

omegatrix
  • 99
  • 1
  • 4