Gabriel Nazoa Gabriel Nazoa - 2 months ago 17
HTML Question

Making a Javascript slideshow with wordpress

I'm making my first steps learning to code. I made some courses about html, css, javascript, php and MySql, and now, I decided to continue learning from the practice while I build a Wordpress child theme.

The thing is that I am building an image slideshow. And to start understanding how to make it I found this: http://www.w3schools.com/w3css/w3css_slideshow.asp.

It's a simple and useful slideshow. It's really nice! But there are some problems if I want to implement it in Wordpress.

I made a post type and using the Advanced Custom Fields plugin I created a Repeater Field. So that code would be something like this in Wordpress:

<?php get_header(); ?>

<script>

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
showDivs(slideIndex += n);
}

function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}

</script>


<?php


if( have_rows('image') ):

while ( have_rows('image') ) : the_row();


if( get_sub_field('subimage') ) :

echo '<div class="mySlides">' . get_sub_field('subimage') . '</div>';
endif;

endwhile;


endif;

?>

<a class="home-btn-left" onclick="plusDivs(-1)">❮</a>
<a class="home-btn-right" onclick="plusDivs(1)">❯</a>


</div>

<?php get_footer(); ?>


It works almost perfect! But now I have two problems:

1) Once I load my page to see the template. I see the first image overlaying the last image. I don't know why:

enter image description here

2) At the end of the slideshow there is an empty slide. It looks like I have an empty subfield but no, I don't have empty subfields. I don't know why there is an empty slide.

Do you have some recommendation?

Thank you

Answer

I think the problem is the last closing DIV </div> just before your get_footer(). It's a simple html markup error that causes the browser to fail. Your code should look like this:

<?php get_header(); ?>

<script>

var slideIndex = 1;

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}

</script>


<?php

if( have_rows('image') ):
  while ( have_rows('image') ) : the_row();
    if( get_sub_field('subimage') ) :
      echo '<div class="mySlides">' . get_sub_field('subimage') . '</div>';
    endif;
  endwhile;
endif;

?>

<a class="home-btn-left" onclick="plusDivs(-1)">❮</a>
<a class="home-btn-right" onclick="plusDivs(1)">❯</a>

<script>
  showDivs(slideIndex);
</script>

<?php get_footer(); ?>

Please let me know if this doesn't fix your problem.

Comments