The slideshow feature on W3 Schools does not start automatically when the page loads

After following the W3Schools tutorial to create a slideshow, I found that the animations are working correctly. However, only three dots appear on the screen and I have to manually click on one of them to view the pictures.


var slideIndex = 0;
showSlides(slideIndex);

function plusSlides(n) {
    showSlides(slideIndex += n);
}

function currentSlide(n) {
    showSlides(slideIndex = n);
}

function showSlides(n) {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    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(" active", "");
    }
    slides[slideIndex-1].style.display = "block";
    dots[slideIndex-1].className += " active";

* {box-sizing:border-box}

.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}

.mySlides {
display: none;
}

.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}

.next {
right: 0;
border-radius: 3px 0 0 3px;
}

.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}

.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}

.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}

.dot {
cursor:pointer;
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}

.active, .dot:hover {
background-color: #717171;
}

.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}

@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}

@keyframes fade {
from {opacity: .4}
to {opacity: 1}

<div class="slideshow-container">
    <div class="mySlides fade">
        <div class="numbertext">1 / 3</div>
        <img src="images/slideshow/canarywharf.jpg" style="width:100%">
        <div class="text">Our headquarters in London, England.</div>
    </div>

    <div class="mySlides fade">
        <div class="numbertext">2 / 3</div>
        <img src="images/slideshow/new_york.jpg" style="width:100%">
        <div class="text">The view from our offices in New York, USA.</div>
    </div>

    <div class="mySlides fade">
        <div class="numbertext">3 / 3</div>
        <img src="images/slideshow/frankfurt.jpg" style="width:100%">
        <div class="text">Our offices in Frankfurt, Germany.</div>
    </div>

    <a class="prev" onclick="plusSlides(-1)">❮</a>
    <a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>

<div style="text-align:center">
    <span class="dot" onclick="currentSlide(1)"></span>
    <span class="dot" onclick="currentSlide(2)"></span>
    <span class="dot" onclick="currentSlide(3)"></span>
</div>

Answer №1

It seems like the issue you're facing is caused by the javascript code being loaded in the head section, which can result in the code running before the DOM is fully loaded.

A quick fix for this is to move the javascript code above the </body> tag so that it's executed only after the DOM has been completely loaded.

Another solution is to use jQuery to check if the document is ready before executing the code. For example:

$( document ).ready(function() {
   showSlides(slideIndex);
});

However, I personally recommend placing the javascript code at the bottom of the document to avoid relying on additional libraries like jQuery. This not only improves performance but also reduces any visual delays experienced by end users when rendering the page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Position the background of the container in the center and keep it

I am trying to create a fixed background header using the following CSS properties: header { margin: 0; padding: 0; width: 100%; height: 300px; display: block; background-image: url('...'); background-repeat: no-repea ...

How to retrieve the length of data in Angular without relying on ng-repeat?

I am currently working with Angular and facing a challenge where I need to display the total length of an array without using ng-repeat. Here is the situation: I have a default.json file: { { ... "data": [{ "name":"Test", "erro ...

Exploring the functionality of a Vue component designed solely through a template

I currently have a basic Vue application set up: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'& ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Creating a Piechart in Kendo UI that is bound to hierarchal remote data

I am facing an issue with binding remote data to a pie chart while managing a grid with dropdown sorting options. The grid is working fine, but I am unable to display the hierarchical data on the pie chart as categories. <!DOCTYPE html> <html> ...

What are the steps to utilize WebRTC in transmitting a real-time webcam feed from the user interface to the server?

Currently, I am in the process of developing a simple Streamyard alternative that can capture live webcam streams from users' browsers and transmit them to the backend for further processing and conversion into the necessary format for streaming on pl ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

I can't seem to figure out which of these 4 statements is free of syntax errors

Can you identify which code block does not contain a syntax error? Out of the 4 options below, one of them is free from any syntax mistakes. alert("hello "+3+" times); alert("hello "+3 times); alert("hello +3+ times"); alert("hel ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

Removing the Yellow Highlight on Input Field Following Email Autocomplete in Chrome

My username-password form is styled and working perfectly, but there's an issue that arises when I log in multiple times. Chrome automatically fills in my email, turning the username textbox yellow. It doesn't seem to happen with Firefox or Safar ...

Continuously iterate through collection as it expands over time

As I cycle through an array, I'm performing additional actions that could potentially prolong the loop if new elements are added to the array during iteration. (I understand it's not recommended to modify the object being iterated over, but pleas ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Having trouble with uploading images using Form.File in React?

I'm facing an issue with my React code for uploading an image. It doesn't seem to be working and I can't figure out why. Can someone please assist me? return ( <div> <FormContainer> <h1>Edit Product& ...

The MaterialUI FormControl API TextField is experiencing an issue where the onClick event does not trigger on the initial click

I am currently working on a React application where I have integrated a MaterialUI Form Control API TextField. However, I am facing an issue with the Select tag as the onClick method is only firing after the first click. There are no hidden CSS properties ...

Use CSS specifically for codeigniter viewpage

I am unsure if it is possible, but I would like to load CSS and JavaScript within a view page instead of on include.php. Currently, the CSS file is loading on include.php and it is working correctly. What I want to achieve now is to load it directly inside ...