Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's permissible to call two distinct JS files in one HTML document. What's even stranger is that when I split the two image sliders into separate HTML documents and called their respective JS files, both worked flawlessly. It's a bit perplexing for me as I'm relatively new to this.

HTML

<video src="./pics/acecs2.mp4" muted loop autoplay controls></video>


      </section>
      <div class="bowl-container">
      <div class="slider-wrap">
        <div class="slider">
          <div class="slider-item">
            <div class="img-div"></div>
          </div>
          <div class="slider-item">
            <div class="img-div"></div>
          </div>
          <div class="slider-item">
            <div class="img-div"></div>
          </div>
          <div class="slider-item">
            <div class="img-div"></div>
          </div>
          <div class="slider-item">
            <div class="img-div"></div>
          </div>
        </div>
      </div>
    </div>;





    <section class="showcase2">


      <video src="./pics/ace3.mp4" muted loop autoplay controls></video>


    </section>
    <div class="bowl-container2">
    <div class="slider-wrap2">
      <div class="slider2">
        <div class="slider-item2">
          <div class="img-div2"></div>
        </div>
        <div class="slider-item2">
          <div class="img-div2"></div>
        </div>
        <div class="slider-item2">
          <div class="img-div2"></div>
        </div>
        <div class="slider-item2">
          <div class="img-div2"></div>
        </div>
        <div class="slider-item2">
          <div class="img-div2"></div>
        </div>
      </div>
    </div>
  </div>;



      <script src="app.js"></script>
      <script src="app2.js"></script>

app.js

let sliderWrap = document.querySelector('.slider-wrap');
let slider = document.querySelector('.slider');
let clonesWidth;
let sliderWidth;
let clones = [];
let scrollPos = 1
let sliderHover = false;
let req;1
let items = [...document.querySelectorAll('.slider-item')];
let images = [...document.querySelectorAll('.img-div')];


images.forEach((image, idx) => {
    image.style.backgroundImage = `url(./pics2/${idx+1}.jpg)`
})

items.forEach(item => {
    let clone = item.cloneNode(true);
    clone.classList.add('clone');
    slider.appendChild(clone);
    clones.push(clone);
})

sliderWrap.addEventListener('mouseover', () =>{
    sliderHover = true;
})

sliderWrap.addEventListener('mouseleave', () =>{
    sliderHover = false;
})

function getClonesWidth(){
    let width = 0;
    clones.forEach(clone => {
        width += clone.offsetWidth;
    })
    return width;
}


function scrollUpdate(){
    if(window.innerWidth > 760){
        sliderWrap.style.overflow = 'hidden';
        if(!sliderHover){
            scrollPos -= .4
        }

        if(clonesWidth + scrollPos >= sliderWidth){
            
            scrollPos = 1;
        }else if(scrollPos <= 0){
            
            scrollPos = sliderWidth - clonesWidth - 1
        }
        slider.style.transform = `translateX(${-scrollPos}px)`

        req = requestAnimationFrame(scrollUpdate)
    }else{
        sliderWrap.style.overflow = 'scroll';
    }

}


function onLoad(){

    calaculateDimensions()
    scrollPos = 1;
    scrollUpdate();
}

function calaculateDimensions(){

    sliderWidth = slider.getBoundingClientRect().width;
    clonesWidth = getClonesWidth();
}

onLoad();

app2.js

let sliderWrap2 = document.querySelector('.slider-wrap2');
let slider2 = document.querySelector('.slider2');
let clonesWidth2;
let sliderWidth2;
let clones2 = [];
let scrollPos2 =1
let sliderHover2 = false;
let req2; // request animation frame reference
let items2 = [...document.querySelectorAll('.slider-item2')];
let images2 = [...document.querySelectorAll('.img-div2')];


images2.forEach((image, idx) => {
    image.style.backgroundImage = `url(./pics3/${idx+1}.jpg)`
})

items2.forEach(item => {
    let clone = item.cloneNode(true);
    clone.classList.add('clone');
    slider2.appendChild(clone);
    clones2.push(clone);
})

sliderWrap2.addEventListener('mouseover', () =>{
    sliderHover2 = true;
})

sliderWrap2.addEventListener('mouseleave', () =>{
    sliderHover2 = false;
})

function getClonesWidth(){
    let width = 0;
    clones2.forEach(clone => {
        width += clone.offsetWidth;
    })
    return width;
}


function scrollUpdate(){
    if(window.innerWidth > 760){
        sliderWrap2.style.overflow = 'hidden';
        if(!sliderHover2){
            scrollPos2 -= .15
        }

        if(clonesWidth2 + scrollPos2 >= sliderWidth2){
            
            scrollPos2 = 1;
        }else if(scrollPos2 <= 0){
            
            scrollPos2 = sliderWidth2 - clonesWidth2 - 1
        }
        slider2.style.transform = `translateX(${-scrollPos2}px)`

        req2 = requestAnimationFrame(scrollUpdate)
    }else{
        sliderWrap2.style.overflow = 'scroll';
    }

}


function onLoad(){

    calaculateDimensions()
    scrollPos2 = 1;
    scrollUpdate();
}

function calaculateDimensions(){

    sliderWidth2 = slider2.getBoundingClientRect().width;
    clonesWidth2 = getClonesWidth();
}

onLoad()

Answer №1

It is recommended to include the 2 suffix when scoping your functions. Another option is to incorporate the type="module" attribute. By doing this, you can eliminate the need for any 2 suffixes except in the context of HTML.

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 reason behind a taller button when using a single line span?

Currently experiencing some strange effects with the radio buttons I'm working on. My goal is to have them all be the same size, but they are coming out different depending on whether the text within the button spans one or two lines. I've been a ...

How can I import tamplateData into my JavaScript files in Docpad?

Looking for a DocPad plugin that can preprocess JS files and utilize templateData variables and helpers to access configuration values. While experimenting with Hogan, I managed to retrieve the variables but encountered difficulty in invoking the helpers. ...

The settimeout function does not seem to function properly within the context of

Currently, I am facing an issue with implementing block UI for blocking a specific div when a button is clicked. The problem I am encountering is that even though I want the blocked div to be unblocked after a certain delay, it remains permanently blocked ...

Issues with WordPress's multiple menu functionality not functioning as expected

I've been working on setting up multiple menus in WordPress, and I've run into a little issue. I managed to create the menus, assign them to their respective locations, and save them successfully. However, when I try to call the footer menu, it e ...

The 'Image' component does not have a propType defined for the native prop 'RCTImageView.overlayColor' with a native type of 'number'

Greetings, I am encountering an issue while attempting to run my react native application on Android. The app has been functioning flawlessly on iOS for several months, but this is our first endeavor at utilizing it on Android. We are using react-native .1 ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

Sharing styles between ReactJS and Material-UI - best practices

I am currently facing an issue where I need to share styles across my entire web application. Here is the Problem: I have been using makeStyles in a repetitive manner as shown below: In component_A.js const useStyles = makeStyles({ specific_style: { ...

What is the best way to merge the value of an input field (contained in an array) with another input field before submitting the form

Currently, I am in the process of editing the data in a form's input field. I know that submitting form data this way is not ideal, but I encountered a challenge with getting the value from a datetimepicker into the ng-model. Specifically, I was able ...

Creating a full-width menu with Material UI - a step-by-step guide

I am currently working on creating a mobile menu that spans the full width of the screen. Despite my efforts, it seems like I might be misunderstanding something as my CSS rules are not being applied correctly. Here is a live code example for reference: ...

Looking for assistance in creating a unique jQuery validation function tailored to your

Looking at my form attribute, it appears as follows: onsubmit="return validateForm(this);" Additionally, I have a jQuery function set up like this: function validateForm(form) { $(form,"input").each(function() { if($(this).length < 1) { ...

Adaptive design exhibits varying appearances across various screen sizes

Currently, I am working on a responsive design WordPress site and here is the markup: <div class="contact-wrap"> <div class="contact-number">123-456-7890</div><!--.contact-number--> <div class="user-login"><a href="#"& ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Rails Polymer is experiencing a glitch where the CSS and Polymer elements are not displaying correctly until a page refresh is

Whenever I first load a page, my polymer elements (like paper-input) fail to load their CSS properly. Here is an example of how the page looks before and after refreshing: https://i.sstatic.net/vsIpE.pnghttps://i.sstatic.net/YAFjP.png Below is the code sn ...

Guide on deleting objects based on their IDs when the IDs are stored in a separate array using JavaScript

I have two separate arrays. One array contains only integers as IDs (from a searchBox) and the other array contains objects, such as: categories = [1, 2, 5, 8]; items = [ { title: 'Hello', description: 'any description you want', cat ...

Issue with Parsley validation not functioning as expected

I have implemented parsley.js to validate my form, but I am facing an issue when trying to validate a checkbox using the data-mincheck attribute. Below is the snippet of my code: <form data-validate="parsley"> <p>Please choose at least 2 ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...