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

Interacting with iView UI dropdown menu items

I'm attempting to create a click event in iView ui. Here's my code: <DropdownMenu slot="list"> <DropdownItem @on-click="markAsRead">Mark as read</DropdownItem> </DropdownMenu> The function markAsRead isn't exec ...

Exploring outside iframe data

My webpage includes an iframe A with a src attribute that links to a URL containing another embedded iframe B. I'm trying to figure out if it's possible to access the src of this nested iframe B. However, it appears that browser security measures ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

Changing the Title of UI Tabs

I am facing an issue with setting the title in tabs, as the title is appearing behind the background. If I set background: transparent; in the #tabss .ui-tabs-nav class, then my title shows up properly. Otherwise, it gets displayed behind the background. ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

Implementing $modal.open functionality in AngularJS controller using Ui-Bootstrap 0.10.0

Is there a way to properly call $modal.open from the controller in AngularJS since the removal of the dialog feature in ui-bootstrap 0.1.0? What is the alternative method available in the current version? In previous versions like 0.1.0, it was simply don ...

The MAC slideshow circles at the bottom have been mysteriously chopped off

Utilizing the popular JQuery plugin Cycle for a slideshow on this site: bybyweb.com/pbm An issue has arisen - everything functions as expected on windows (across all major browsers), BUT on MAC (running lion 10.7.5, tested on one machine so far; unsure of ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

Differences in the way websites scroll on Chrome compared to Safari and Firefox

Currently, I am in the process of developing a rendering system for my application that extracts objects from a collection and processes them through JavaScript templates to generate additional children as the user scrolls through the page. The system is d ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

Is there a way to completely remove all styling from a specific child element?

Struggling with a drop-down menu issue - the parent element has a border, but I don't want that style to be inherited by the child sub-menu. Despite my attempts to remove the border using border: 0px, it's not working as expected. Is there any wa ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

Preventing jQuery plugin from overriding default settings

I have created a jQuery plugin using the nested namespace pattern, inspired by the design template found in Addy Osmani's book. The plugin is a simple gallery and everything seems to be functioning correctly. However, I am facing an issue when attemp ...

Enhance security in AngularJS by enabling data sharing between controllers and implementing callback functions for authentication

Currently, I am engaged in building an Angular front-end application, aiming to keep things simple without relying on tools like breeze or restangular while still maintaining code integrity. However, I have noticed that my code tends to become overly compl ...

Using -webkit-hyphens: auto in Safari does not function properly when the width is set to auto

I have a situation with an h3 element where I am unsure of its width. As a result, the width is set to auto by default. However, I need the text inside this element to have hyphenation applied to it. This h3 element is within a flex container along with an ...