I've been trying to create my own slider for my blog posts recently but I cannot get it to work. I have tried different code online but none of them rotate my list items(These are created by the post loop). Below is code I tried from W3Schools but it shows an error Uncaught TypeError: Cannot read property 'style' of undefined at carousel
Here is my function from functions.php which I call on index.php to display the posts:
function displayBlogSlider() {
$args = array(
'posts_per_page' => 3
);
// the query
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<div class="slider js--slider">
<!-- pagination here -->
<ul class="slider-inner js--slider-inner">
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="slider-item js--slider-item">
<div class="slider-info">
<?php blog_set_featured_background(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p>By <a href="<?php the_author(); ?>"><?php the_author(); ?></a></p>
<p><?php the_date(); ?> — <a href="#"><?php comments_number(); ?></a> ● <a href="#"><?php the_category(); ?></a></p>
</div>
</li>
<?php endwhile; ?>
</ul>
<!-- end of the loop -->
<div class="slider-nav">
<a href="#" class="nav-prev js--nav-prev"><</a>
<a href="#" class="nav-next js--nav-next">></a>
</div>
</div>
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;
}
function blog_set_featured_background() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full, false );
if ($image_url[0]) {
?>
<style>
.slider-inner {
height:100%;
margin:0!important;
}
.slider-inner {
background: linear-gradient( rgba(0, 0, 0, 0.20), rgba(0, 0, 0, 0.80)), url(<?php echo $image_url[0]; ?>) #000 no-repeat;
background-position: center;
background-size: cover;
}
</style>
<?php
}
}
And here is my javascript for making the list items rotate(similar to W3S):
var myIndex = 0;
carousel();
function carousel() {
var i;
var listItem = document.getElementsByClassName("js--slider-item");
for(i = 0; i < listItem.length; i++) {
listItem[i].style.display = "none";
}
myIndex++;
if(myIndex > listItem.length) {
myIndex = 1;
}
listItem[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
If there is a better way of making a carousel for wordpress blog posts, I'll accept all advice and info. But I want to create it myself, I don't want to make use of a plugin. Also, I'd prefer pure javascript since I am still learning it.
I want to create something similar to the first slider here - https://manohara.incredibbble.com/