What is the best way to initiate a slideshow using an external .js file?

Having an issue with my slideshow. When I put the CSS and JavaScript code in the same page, it kind of "works" but quickly goes transparent, which is not ideal for me. I prefer keeping things organized with separate files - one for each. However, when I move the code to an external .js file, the images don't load. The CSS works fine, but the JavaScript just won't run. Any help would be appreciated?

Here's the code:

/*JavaScript*/

var slideIndex = 1;
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";
}
/*CSS*/

* {box-sizing:border-box}

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

.mySlides {
    display: none;
}

* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}
.mySlides {display:none}

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

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

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

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

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.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;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-dura...
<!--HTML-->

<head>
<script type="text/javascript" src="Java y CSS/ElagarWebJS.js"></script>
</head>

<div class="slideshow-container">
  <div class="mySlides fade">
    <div class="numbertext">1 / 3</div>
    <img src="Multimedia/Bloc o Note.png" style="width:100%">
    <div class="text">Cualquiera de estos dos es buena alternativa, pero el obvio ganador es Notepad++ con sus distintos leguajes y su autocompletación</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 3</div>
    <img src="Multimedia/IE o CH.png" style="width:100%">
    <div class="text">Aunque ambos funcionan bien, Chrome gana este round pues esta a la vanguardia con los scripts, cookies, y bueno... es Google</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 3</div>
    <img src="Multimedia/Ganas.png" style="width:100%">
    <div class="text">Puede llegar a ser muy, Muy, MUY estresante asi que cuidado... Diviertete</div>
  </div>

  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</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

Perhaps the issue lies in either incorrectly organizing the files or not properly referencing them.

My recommendation is to consider utilizing OwlCarousel for its responsiveness, user-friendliness, and straightforward implementation.

This could potentially streamline the process and save you valuable time.

Answer №2

Indeed, it is advisable to have an external file for your code rather than embedding it directly into the page. In essence, you are instructing your code to fetch the relevant information from elsewhere.

<link rel="stylesheet" type="text/css" href="mystyle.css">

This should be included in the header section of your HTML.

Within the body tags, ideally before closing them:

<body> ...


...

<script src="myscripts.js"></script>

</body>

There may be differing views on where to place your JavaScript file - either within the body or the header. However, both locations will function correctly.

Just ensure that you provide the correct path and filename, like so:

<script type="text/javascript" src="Java y CSS/ElagarWebJS.js"></script>

In this example, there should be a folder named "Java y CSS" within your current directory, containing the file "ElagarWebJS.js".

Is this all the code you have? Where is your body content and how does your CSS style get applied if it's not being called?

By following these instructions, I hope the issue will be resolved for you :)

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

When using v-for to render an array list fetched from AsyncData, an error is thrown: The virtual DOM tree rendered on the client-side does not match the one

For my application, I am utilizing Nuxt.js. On one of the pages, I am using AsyncData to fetch an array of data objects from my API asynchronously. These data objects are then rendered in my template using v-for. Everything is functioning properly until I ...

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

List-style-type outside of a table's boundaries

I recently experimented with using <ol> as list elements within a table in order to dynamically insert new table rows. <table> <thead> <tr> <th>head</th> <th>head</th> <th>h ...

JavaScript Evaluation Error

try { eval(somejavascript); } catch(e) { console.log(e); } When I encounter runtime errors like: TypeError: Cannot call method 'leftPad' of undefined I wonder if there is any way to debug this error. Specifically, I'm looking for ...

Fundamentals of Angular 2

It's not just an inconvenience, but something that truly frustrates me. Could someone please clarify the following: Why does Angular load these scripts in HTML directly from node_modules https://i.sstatic.net/D8UrG.png Why am I unable to simply imp ...

Angular material chips showcase a row of five chips

I am working with the basic mat-chips from angular material and I want to arrange them in rows of five without increasing their size: Chip1 Chip2 Chip3 Chip4 Chip5 ..................(space left) Chip6 Chip7 Chip8 Chip9 Chip10 ...............(space le ...

Issue: Package 'cairo' not located on EC2 Bitnami MEAN server

Setting up my MEAN application on a Bitnami server has been quite a challenge. During the installation of dependencies, I encountered an error that I just can't seem to resolve. Despite following the instructions provided in the error message, I am st ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

What is the best way to use jQuery to dynamically highlight all instances of a word as the user types, both new and existing?

I am currently developing a user-friendly note-taking tool that automatically highlights specific keywords as the user types, making it easier for them to locate important information later on. I have implemented a keyup() function that monitors a text ar ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Name of Document (changing from php to ?)

Greetings! Currently, I am utilizing PHP to include the document name as an example. folder/<?phpecho basename(__FILE__, '.' . pathinfo(__FILE__, PATHINFO_EXTENSION));?>_button.png I have observed that using PHP for this purpose and havin ...

Display PickerIOS when a button is clicked in a React Native application

I am a beginner with the react framework and I'm trying to implement a PickerIOS component on button click. However, I'm having trouble understanding how to call other classes upon an event. I found this code snippet on the React Native site: v ...

Run the script within the Angular scope

Hey there! I'm having an issue passing a JavaScript code through Angular scope, but when it renders on the view page, it's displayed as text. I even attempted using ng-Sanitize, but unfortunately, that didn't solve the problem. &lt;div ...

Ways to determine if two variables point to the same object in javascript

Recently, I started learning JavaScript and came across the spread operator. From what I learned, it deep copies the top-level elements of an array or object but only shallow copies the nested arrays or objects. To visualize this concept in action, I tried ...

Organizing a list based on the text within span elements using either jQuery or underscore

I'm a bit confused about how to arrange an unordered list by the content of the span within each list item. Here is my HTML code: <ul id="appsList"> <li><span>aa</span> <span class="sort">androi ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...