When using jQuery in HTML, it runs successfully within the header section but it fails to execute when placed in an external JavaScript

Although this question has been asked previously, I am still a bit confused about the issue at hand. In my index.html file, I have a script tag that links to an external JS file. When only that script tag is present, the JS does not seem to function. However, if I copy and paste the JS into its own script tag within the HTML header, it works perfectly fine. It seems like there might be something missing in regards to Jquery.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.2.0.js"></script>
    <link rel="stylesheet" href="FinalProjectCss.css">
    <title>Dustin Naylor - Final Project</title>
<script src="FinalProjectJS.js"></script>
<script>
    $(document).ready(function(){
        $(".section").click(function(){
            if($(this).next().is(":hidden")) {
                $(this).next().slideDown("fast");
            } else{
                $(this).next().hide();
            }
        });
    });
</script>


</head>
<body>

<span class="section"><a href="#" style="cursor:pointer;">Click Me</a></span>
<div class = "hiddenDiv">
    Oh hey there.
</div>
</body>
</html>

The code inside the last script tag, which contains jQuery functions, has been exactly duplicated into its separate JS file named FinalProjectJS.js. In its current state within the HTML file, this code functions as intended. However, when removed from the HTML file, it no longer works properly. Apologies for my lack of expertise, as I am relatively new to this. Any assistance would be greatly appreciated! Thank you!

Answer №1

Could you provide the contents of your JQuery file, specifically FinalProjectJS.js? The syntax for calling the external file seems to be correct, so it might be an issue with the file path or the content of the JQuery external file itself. Please ensure that you do not include any <script> tags in that file. You can refer to this example for guidance.

Additionally, in my past experiences working with JQuery, I noticed that changes may not take effect immediately when both HTML and JQuery files are stored locally. It was necessary to host them on a server before seeing the JQuery effects. A developer I collaborated with added some configurations to Google Chrome's properties (target) to enable me to view the JQuery effects without hosting the files on a server.

I apologize for being unable to comment at the moment to seek further clarification on your initial post.

Answer №2

In order for the jQuery snippet to be functional, ensure that the jQuery script tag is added before FinalProjectJS.js.

<script src="https://code.jquery.com/jquery-3.2.1.js"

integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous">

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

Instructions for including a scroll bar in an HTML side menu

Can anyone help me figure out how to add a scroll bar specifically for the left side navigation menu? I've tried adding overflow-y: scroll; in different places, but it hasn't worked so far. I'm still learning web design and have been piecing ...

What could be the source of this JS console error?

Could someone please assist me with understanding why the included error is appearing in the console? I have been learning jQuery for some time now, but still consider myself a novice. Any guidance on how to resolve this issue would be greatly appreciated. ...

Why isn't the footer extending to the edges despite setting margins and other properties?

Feeling a bit lost here. My footer isn't extending to the edges of the window like it should, or so I thought. .footer { height: 200px; bottom: 0px; margin: 0px; left: 0px; right: 0px; padding: 0px; width: 100%; background-color: #E ...

Stop the page from refreshing when the Struts button is clicked - Here's how!

I've included the code below: <s:submit type="input" value="clickme" onclick="func()"/> Inside the func() function, there's an alert("hereee") command. When I click the button, it displays "hereee" in an alert window but also refreshes th ...

"Utilizing Html5 to add text decoration to a div element

When working in html5, you can wrap a div inside an anchor tag. But I am facing an issue with the text decoration as text-decoration:none doesn't seem to work. <div id="messageconv"> <a href="#"> <div class="messageconv"> ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

Align Bootstrap 4 div.card horizontally in the center

I have a website where I am displaying articles from a database using Bootstrap 4. I want the card blocks (div.card) to be horizontally centered no matter how many there are, with a maximum of 3 blocks per row. I have tried various methods but haven't ...

Utilizing Z-Index with Fixed Positioning and Transitions in CSS

Currently in the process of setting up a fresh portfolio website and utilizing the Onepage Scroll Plugin created by Pete R. Recently, I included a fixed navigation bar and now aiming to have elements within a slide overlapping this navigation. Here's ...

PhantomJS is unable to load content from click events into the DOM

I am currently facing a challenge where testing a click event on an anchor tag to trigger specific DOM transformations is not producing the expected results in PhantomJS. The code seems to work fine in the browser, and I have meticulously reviewed each lin ...

Is there a way to implement jwt.verify() from jsonwebtoken in a React application?

Every time I attempt to use the jwt.verify() or jwt.decode() function in my React project, it keeps throwing a multitude of errors. The errors that I encounter are: ERROR in ./node_modules/jwa/index.js 5:13-30 Module not found: Error: Can't resolve ...

PHP and AJAX: Dealing with Duplicate Row Instances

Check out an Example of Grades Page Having some trouble with PHP and AJAX causing duplicate rows. My goal is to show the total number of units and GPA for each subject, but it keeps adding extra rows. Here's the AJAX code: $.ajax({ traditional: ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

There is no throttleTime function available in Angular 6 within Rx Js

Currently, my Angular 6 project is utilizing angular/cli": "~6.1.5 and rxjs": "^6.0.0. As a newcomer to Angular 6, I decided to dive into the official documentation to enhance my understanding. Here's a reference link I found useful: http://reactivex ...

Avoid having the content below become pushed down by a collapsed navbar

I am utilizing Bootstrap 4.1 My current structure is as follows: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhkt ...

Retrieve information from reader.readAsArrayBuffer

I'm facing an issue with the following code. My goal is to return the uploadData array back to the hello variable, but it's returning as a blank array. Even though the console log shows the correct array of data like {name: 'bob'}, it b ...

The Webservice, as well as the JS and CSS components, are experiencing issues when trying to function on a

I am looking to implement https on just one page of my website, "securepage.aspx". My website is located at The secure page will be accessed via All my resources such as JS/Images are stored in the assets folder and my web services are in the commonwebs ...

Is it necessary to reset the toggle, or should it be reset upon clicking another element?

I am in the process of setting up a click-to-show menu with two separate options for men and women. When users click on the "men" menu, it should display one set of options, while clicking on the "women" menu should display another. If one menu is clicke ...

Adjust the transformation with jQuery

How can I apply the following value to the transform CSS property of a div tag: translate(-50%, -50%) translate(-100px, -300px)? I attempted to use the following jQuery command to set the value: jQuery('.content').css('transform', &ap ...

Utilizing React JS to Activate the Glyphicon Calendar Icon on Click

Could someone please advise on how to make the calendar glyphicon activate the datetime picker upon clicking? I have a button currently but it is not functional. I've been searching for React-specific solutions without success. <div className={cla ...

Passing the value selected from a datepicker to PHP without refreshing the page through the use of XMLHttpRequest: Guide

Is it possible to transfer the datepicker value to PHP without reloading the HTML page by using XMLHttpRequest()? The intention is to utilize this date value for a subsequent query and present it on the same HTML page. <input type="date" id="month" o ...