What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file:

<!DOCTYPE html>
<!--
-->
<html>
    <head>
        <script src="java_script.js"></script>
        <link rel="stylesheet" type="text/css" href="carousel.css">
        <link rel="stylesheet" type="text/css" href="vertical_slider.css">
        <link rel="stylesheet" type="text/css" href="glow-effect.css">
        <script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
        <script src="jquery.carouFredSel-6.0.4-packed.js" type="text/javascript"></script>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>
    <body>
        <div>TODO write content</div>

        <div id="wrapper">
    <div id="carousel-wrapper">
        <img id="shadow" src="img/gui/carousel_shadow.png" />
        <div id="carousel">
            <span id="pixar"><img src="img/large/pixar.jpg" /></span>
            <span id="bugs"><img src="img/large/bugs.jpg" /></span>
            <span id="cars"><img src="img/large/cars.jpg" /></span>
            <span id="incred"><img src="img/large/incred.jpg" /></span>
            <span id="monsters"><img src="img/large/monsters.jpg" /></span>
            <span id="nemo"><img src="img/large/nemo.jpg" /></span>
                        <span id="radar"><img src="img/large/radar002665.png" /></span>
            <span id="rat"><img src="img/large/rat.jpg" /></span>
            <span id="toystory"><img src="img/large/toystory.jpg" /></span>
            <span id="up"><img src="img/large/up.jpg" /></span>
            <span id="walle"><img src="img/large/walle.jpg" /></span>
        </div>
    </div>
    <div id="thumbs-wrapper">
        <div id="thumbs">
            <a href="#pixar" class="selected"><img src="img/small/pixar.jpg" /></a>
            <a href="#bugs"><img src="img/small/bugs.jpg" /></a>
            <a href="#cars"><img src="img/small/cars.jpg" /></a>
            <a href="#incred"><img src="img/small/incred.jpg" /></a>
            <a href="#monsters"><img src="img/small/monsters.jpg" /></a>
            <a href="#nemo"><img src="img/small/nemo.jpg" /></a>
                        <a href="#radar"><img src="img/small/radar002665resized.jpg" /></a>
            <a href="#rat"><img src="img/small/rat.jpg" /></a>
            <a href="#toystory"><img src="img/small/toystory.jpg"  /></a>
            <a href="#up"><img src="img/small/up.jpg" /></a>
            <a href="#walle"><img src="img/small/walle.jpg" /></a>
        </div>
        <a id="prev" href="#"></a>
        <a id="next" href="#"></a>
    </div>
</div>
    </body>
</html>

Including both css and javascript files, with java_script.js and vertical_slide.css being called. The javascript works fine if inserted directly into the HTML file, but once moved to a separate file (java_script.js), it stops working properly. Images are not displayed correctly and the functionality is broken.

Upon inspecting elements, there are no errors shown, yet the script is not functioning as intended.

The javascript file contains:

(function test() {

    ('#carousel').carouFredSel({
        responsive: true,
        circular: false,
        auto: false,
        items: {
            visible: 1,
            width: 200,
            height: '56%'
        },
        scroll: {
            fx: 'directscroll'
        }
    });

    ('#thumbs').carouFredSel({
        responsive: true,
        circular: false,
        infinite: false,
        auto: false,
        prev: '#prev',
        next: '#next',
        items: {
            visible: {
                min: 2,
                max: 6
            },
            width: 150,
            height: '66%'
        }
    });

    ('#thumbs a').click(function() {
        ('#carousel').trigger('slideTo', '#' + this.href.split('#').pop() );
        ('#thumbs a').removeClass('selected');
        (this).addClass('selected');
        return false;
    });

});

The function has been named "test", whereas previously it was anonymous. All functions that included "$" were causing errors and were therefore removed.

The accompanying CSS file looks correct without any obvious issues. It seems like the problem lies specifically within the javascript file when moved externally from the HTML document.

Answer №1

Make sure to arrange the order of your script files correctly in order to avoid any potential issues with undefined variables.

<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="jquery.carouFredSel-6.0.4-packed.js" type="text/javascript"></script>
<script src="java_script.js"></script>

Don't forget to include the $ sign back into your script file to resolve the issue.

Answer №2

To organize your JavaScript functions, consider creating a separate .js file to contain all of them and then include the file in your HTML page.

Answer №3

To ensure proper organization, save all Javascript code in a file with a .js extension and place this file in the same directory as your HTML file. Next, include the following line within the <head></head> section of your HTML page:

<script src="js_file_path"></script>

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

How can you ensure that an inline <span> automatically moves to the next line if it is too wide?

Struggling with bootstrap badges and trying to arrange <span> elements to appear on the next line when they are too large. On mobile, my page looks like this: Joe Bloggs (Bigger Badge) Joe Bloggs Brother (SMALL BADGE) How can I configure it so t ...

What is the best way to organize text within messages?

Hey there! I have a messaging app with arrays of messages. [{"id":4, "user_id":1, "messageable_id":3, "messageable_type":"conversation", "text":"Text 1", "action":null, "target_id":null, "created_at":"2019-06-17 15:47:55", "updated_at":"2019-06-17 15:47:5 ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...

Unlinked Checkbox in Angular Bootstrap Modal Controller

I am currently utilizing the modal feature from Bootstrap 3's Angular fork, and I am facing an issue with using a checkbox within the modal and retrieving its value in my main controller. The checkbox value is properly bound in the view but not in th ...

Steps to calculate the total number of rows in a datatable

I have implemented a datatable in my project, and I need to find out the total number of rows in the table when it is loaded. Here's the snippet of code I am currently using: $(document).ready( function() { $('#jobSearchResultTable').data ...

Striped shadows in React Three Fiber

Currently in the process of developing a basic 3D object viewer website using Next.js and React-Three-Fiber. Everything was running smoothly until I added a DirectionalLight instance and attempted to make all meshes receive shadows. https://i.sstatic.net/ ...

Retrieving all buttons from a webpage and removing those with a specific background-image using JavaScript

Hey everyone, I'm still learning about javascript and other web development languages. My current task is to locate all the buttons on a webpage and remove the ones that have a specific background image. I know about using getElementsByTagName but n ...

To ensure the smooth functioning of a React application running on a Docker container in Ubuntu 16.04, it is

I'm currently in the process of setting up a docker container for running a react app that sends a fetch request to another docker container containing a node server. The deployment is on Ubuntu 16.04, however, after building and deploying the contain ...

What is the best way to display SQL query results in a list upon clicking a tab?

I have imported an SQL file containing a table named student_tb. This table consists of three columns: student_id, student_name, and class_name. To create this SQL table, you can follow the script below: CREATE TABLE `student_tb` ( `student_id` int(11) ...

Guide on using react-highlight-words to emphasize various keywords using different color schemes

I am currently working on implementing a search feature for my React project. At the moment, I am only required to enter a single keyword and search for it within the text. Once found, I need to extract and display the sentences containing this keyword sep ...

Problem with JQuery: Click to reveal the code

Here is some of my JQuery code jQuery('.tpcoupon-reveal').click( function() { jQuery('.inner-code').css('background-color','#FFF'); jQuery('.inner-code').text(jQuery(this).attr('caption')); visit ...

What could be causing the pause function for videos to stop working in Chrome?

Recently, I've encountered an issue with the pause() function in Chrome while trying to stop a video playback. Despite using this method successfully in the past with Firefox, it seems to no longer work on Chrome browsers. I've simplified my code ...

As I scroll, I hope the texts will stay fixed against the backdrop image

Is it possible to make the #home section fixed to the background while scrolling, including all the texts and buttons? I envision it like having texts embedded in an image. The text is located in the middle left of the page (let's keep this as default ...

Having trouble with a Reactjs Facebook login library - update the componentClicked function to be async

Currently, I am working on incorporating Facebook login into my React application using Redux. Within my loginUser.js file, the "FacebookLogIn" component appears as follows: <FacebookLogin appId="375026166397978" autoLoad={true} fields="name, ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Grab Text Class - Python Selenium Automation

I am attempting to extract an element from a webpage using Selenium in Python <span class="_2-1_O"><span dir="auto" class="_1jlxc _3Whw5">Ana Smith</span></span> My goal is to extract the name Ana Smith using Python: contact_name ...

Guide on adding a timestamp in an express js application

I attempted to add timestamps to all my requests by using morgan. Here is how I included it: if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('common')); } After implementing this, the o ...

What methods can Cypress use to validate content containing hyperlinks?

My current task is to develop an automation test that confirms the presence/display of content containing a hyperlink embedded within text. Please refer to the screenshot I have provided for better understanding, as it illustrates the specific content encl ...

Customizing Bootstrap icon with padding, background color, and radius settings

Struggling with Bootstrap Icons and Bootstrap 5, I attempted to create a perfect circle background behind an icon by setting padding, background color, and a rounded circle radius. The code I used was <i class="bi-globe-americas text-white p-3 bg-p ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...