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

What is the best way to add color to a Table Header?

I'm working on a HTML/CSS table and I want the header row to have a specific background color. Below is my code: <table class="contentTable"> <tr class="contentTableHeader"> <th>No.< ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

Encountering difficulty accessing the router during testing in Next.js

Hello, I'm currently attempting to test a scenario where when a button is pressed, it should redirect to '/'. Normally this works fine, but during testing it fails and shows the following error: Cannot read properties of null (reading ' ...

Creating a string specifically for implementing regular expressions in JavaScript

I'm currently working on a custom jQuery plugin known as jQuery-Faker. This plugin is designed to produce fake data for populating form fields based on their respective field names. One of the tasks I have set out to accomplish is generating phone num ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

What is the best way to toggle the visibility of fields on a modal in a Ruby on Rails

I am working on an application that utilizes Rails 4.1 and Ruby 2.1.2. The show.html.erb view for the Assignment Model in this application is as follows: <h1><%= "#{'Source URL'}"%> <div class="source-url"><%= @assignment.so ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

Having issues with passing data correctly in a jQuery AJAX PHP login system

I am encountering a Failure object Object notification. Despite reviewing various examples, I am unable to pinpoint the error. My suspicion is that my AJAX setup is not configured correctly. The PHP code seems to be in order as it interacts with a local da ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...

Are there any available tools or scripting methods for accommodating various vendor prefixes?

My preference is to use standard CSS rules for different styles that include various vendor prefixes. To test, I would start with the following: border-radius: 5px; box-shadow: 0px 0px 4px 0px #fff; transform: rotate(90deg); For the final version, I woul ...

Interactions in JQuery UI

Having issues with jQuery UI events. I have sliders in my app and occasionally need to adjust the "min" option. However, I'm facing a problem where the change() event is not triggered after making the adjustment. I would assume that every time the val ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the bu ...

What could be causing this jQuery to fail when attempting to load another function?

Here is a jQuery code that performs 2 actions: The first action automatically reloads the page every 7 seconds (refreshPartial();) The second action inputs text into the chat_box field when a link is clicked. The second action only works if 'refre ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

Utilizing jQuery to Trigger a JavaScript Function in a Separate File

Here is my question: I currently have 2 files: //File1.js function TaskA() { //do something here } //File2.js function TaskB() { //do something here } $(function() { TaskA(); }); The issue I am facing is that the TaskB function in File2.js ...

Aligning a Material UI button to the far right of a row

I am struggling to align a React material-ui button to the right-most of the page and despite trying to use the justify="flex-end" attribute within the following code, it doesn't seem to be working: <Grid item justify="flex-end" ...