The manual controls for the auto slider are failing to take effect

I'm having trouble implementing manual controls for a slider. The auto play feature is working fine, but the prev/next buttons and dots are not functioning as expected. Can someone help me troubleshoot? Here's the code: https://jsfiddle.net/t8ap0gvz/

var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");

showSlides();

function showSlides() {    
var i;    
for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none"; 
}
slideIndex++;
if (slideIndex> slides.length) {slideIndex = 1} 
slides[slideIndex-1].style.display = "block"; 
setTimeout(showSlides, 5000); // Change image every 5 seconds
}

function currentSlide(no) {
var i;    
for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none"; 
}
slideIndex = no;
slides[no-1].style.display = "block";
}

function plusSlides(n) {
var newslideIndex = slideIndex + n;
if(newslideIndex < 4 && newslideIndex > 0){
 currentSlide(newslideIndex);
}
}

Answer №1

As mentioned in the previous response, there was a discussion about optimizing the DOM loading process on JSfiddle. In order to adjust the order in which JavaScript is written, it is recommended to place functions for onclick events after all HTML elements. By default, JSfiddle inserts them in windows.onload, so simply changing the script placement to No wrap - bottom of will resolve this issue.

To implement this change, navigate to LOAD TYPE and select that option.

In actual HTML code, the script tag should be placed at the end of the body, within a script tag.

Answer №2

It seems like the issue arises from the functions being loaded before the HTML. By moving the showSlides() call to a position below, it resolves the problem:

// Ensuring DOM is fully loaded
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    showSlides();
  });
} else {
  showSlides();
}

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

Wrapper Div at the Center

I'm currently working on aligning my webpage in the center using the following CSS: .wrapper { display: flex; align-items: stretch; background: #fafafa; /*max-width: 1520px; */ box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.1); text ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X HTML: <input type="file" id="hotspot" (change)="uploadHotSpot($event)"&g ...

Trying to figure out how to avoid HTML characters in AngularJS? I've come across suggestions to use ng-bind / ng-sanitize for escaping HTML, but I'm struggling to put

As a newcomer to Angular Js, I recently utilized ngx-editor to create a text-area with various formatting styles. However, upon submitting the content, I noticed that HTML tags were also being displayed. I understand that these tags appear when using diffe ...

Process only the $_POST variables that have a specific string prefix

I am currently working on a form that will be handling numerous elements sent via $_POST. A significant portion of these elements, which are too numerous to list individually, have a consistent naming pattern: $_POST['city_1'] $_POST['city_ ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Transitioning from embedded browser to system browser in a Next.js / React.JS application

I'm currently dealing with an issue on my Next.js payment page and could really use some expertise. Here's the situation at hand: My payment page has a QR code that directs users to the payment page created with Next.js. When users scan this QR ...

Margins Disrupt Proper Text Alignment;

(If you know of a simpler solution to this issue, please share!) I am aiming for this website to consist of two text sections, one on each side of the screen. I managed to achieve this successfully by using text alignment and translate3d to shift the tex ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="boxes"> <div class="red" style="width: 300px; height: 300px; color: red"></div> <div class="blue ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

Display a list of items in Angular using ng-repeat, and allow the full description to appear in full width

<div ng-controller = "MyController"> <ul class="items" > <div ng-repeat="item in colors" ng-class="{active:isActive(item)}" ng-click="select(item); whattoshow=!whattoshow"> <li class="col-md-3 col-sm-3 col-lg-3 co ...

Ajax: Why am I receiving an error response instead of a successful one?

It's puzzling why my code is triggering the error function instead of success. The console.log keeps showing me this: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: f ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

Encountering issues with AJAX requests using jQuery

Hey there, I'm attempting to make an AJAX call in a C# page and I'm running into some issues. Below is my jQuery code: $(document).ready(function () { $.ajax({ type: "POST", url: "conteudo.aspx/GetNewPost", data: { i ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Verify if any column within a JSON object has a value of undefined, null, or is empty

Hey there, I'm a newcomer here and couldn't find any information on this topic after searching. Is there a method to scan a JSON object for empty values? For example, is there something like if(json[randomInt()].hasBlanks) that can be used? Or d ...

Including a drop-down arrow or triangle next to the initial button

In the navigation bar displayed below https://codepen.io/shaswat/pen/XzpRXL Is it possible to create a down triangle or arrow next to the "home" link, which changes direction upward when hovered over? How can this be achieved without modifying any HTML e ...

Ways to modify the function to restrict its operation to the specific id, class, or selector

I've created a jQuery function that copies checkbox values to the textarea with the ID #msg. $(document).ready(function(){ $("input:checkbox").click(function() { var output = ""; $("input:checked").each(function() { ...