0

Despite several other solutions, I have yet to find one that actually solves my problem. I have an HTML file containing a header with

    <script type="text/javascript" src="./js/throwaway.js"></script>

and in the body there is a button like so:

    <button onclick="basicAlert()"></button>

and I have the Javascript function basicAlert():

    function basicAlert() {
        alert("this is a test to see if basicAlert runs");
    }

I've been stuck on this for two days now to no avail, but I cannot get the onclick function to execute basicAlert() when the function is in the external file. I can have a script in the HTML holding the function, and it will run flawlessly, but when the function is in the external file, it does not run. Attempted solutions included trying onsubmit (it's a search bar), removing 'type="text/javascript"' (since default is JS anyways), and moving the script src to the different sections of the file, headers, body, at the end, etc. making the path things like "/js/throwaway.js", "../js/throwaway", every combination I could think would make sense. The current file set-up is a Node app.js that references from folder public, which contains the HTML doc and a folder "js" which contains the throwaway program. And yes the file location is correct in relation to the HTML, where it's being referenced. If I could just have the function inside the HTML, I would, but there's going to be several functions, so I don't want to clutter the HTML file.

I'm very new to javascript and HTML, so I would appreciate any assistance. Thanks in advance.

EDIT: someone asked for full relevant code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Spotlight</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript" src="./js/spotifyFunctions.js"></script>
</head>
<body>
<input type="text" class="form-control" id="songSearch" placeholder="Enter Song or Playlist...">
<button id="search" onclick="basicAlert()"><div class="search-icon"><ion-icon name="search"></ion-icon></div></button>
    <script src="link"></script> <!-- There's about 20 of these before the basic alert -->
    <script>
        function basicAlert() {
            alert("throwaway");
        }
    </script>
</body>
</html>

EDIT 2: The Javascript file I have may be the culprit for the errors due to its imports, thanks to those who helped me out in here

import Spotify from "spotify-web-api-js";
const spotifyApi = new Spotify();

//Several functions utilizing spotify API

function basicAlert() {
    alert("this is a test to see if basicAlert runs");
}
console.log("made it");

Throws error in console:

SyntaxError: import declarations may only appear at top level of a module

I can probably figure this one out on my own. Thanks!

  • Is the full content of the Javascript *just* the `function basicAlert`, and nothing else? Do you get any console errors? – CertainPerformance Jan 05 '20 at 04:47
  • While other functions are not just an alert, I have just the basicAlert() function to test whether it is working or not. So yes, that is all that's in this function. There are no console errors as far as I know – Rhett Jarvis Jan 05 '20 at 04:50
  • So it's not all wrapped in a `load` or `DOMContentLoaded` event listener? (that's a common problem) If the function isn't running, there *should* be a console error, that the function isn't defined. There also might be a syntax error - the console *should* be giving you at least one error – CertainPerformance Jan 05 '20 at 04:51
  • Add a `console.log("Made it");` to the bottom of `/js/throwaway.js` - do you see this show on the console when loading the HTML? – Tigger Jan 05 '20 at 04:52
  • nope, it's very cut and dry; and there's no console error displayed with console.log("test"); There's nothing posted to the console actually... Only thing that appears is the Node command I use to start up the app and the "server listening on 8888" that's in the JS – Rhett Jarvis Jan 05 '20 at 04:53
  • I'm extremely doubtful, there really should be at least one error. Can you post a link to the page on which this occurs? – CertainPerformance Jan 05 '20 at 04:56
  • There's no site, it's a personal/school project; and apologies, after clicking the button that has onclick, it reports a "basicAlert" not defined error to the console. – Rhett Jarvis Jan 05 '20 at 04:58
  • 2
    Either `basicAlert` is not defined on the top level, or the Javascript isn't running at all. To start with, check your browser's network tab and fiddle with things until the JS loads properly – CertainPerformance Jan 05 '20 at 05:02
  • And @Tigger, the console log does not display the text when the HTML loads – Rhett Jarvis Jan 05 '20 at 05:03
  • Please show a screenshot of the Network panel after reloading with it open. It will probably show some kind of error loading the script file, although I’d expect one in the console too. – Ry- Jan 05 '20 at 05:05
  • the network tab even displays the throwaway.js with 200 status, like everything is good. Is there anything I need to pair with the function, either at the top of the javascript file or in front of the function (like export or async) to allow the HTML to call on it? – Rhett Jarvis Jan 05 '20 at 05:07
  • on refreshing while opened, it's a 304 status; don't' have enough rep to add a photo. Also can't get it to repeat the 200 status again... – Rhett Jarvis Jan 05 '20 at 05:10
  • 304 is fine, it just means it was cached. (Press Ctrl+Shift+R to do an uncached refresh.) And if you replace the contents of that file with `console.log("Made it");`, nothing shows up? – Ry- Jan 05 '20 at 05:33
  • replacing everything with only that line will make it show up in the console. It sounds like the other functions in the file may have an error then. I'm going to comment out a few to see which one it is real quick. – Rhett Jarvis Jan 05 '20 at 05:41

3 Answers3

0

The easiest way to get your events to fire is to add event listeners in JS

  • Give your button an ID
  • Get the element By ID in JS
  • Add the click event listener

   function basicAlert() {
        alert("this is a test to see if basicAlert runs");
    }

// get the DOM element with JS

let bttn = document.getElementById("MyId");
bttn.addEventListener("click", basicAlert, false);
    <button id="MyId">CLick Me</button>


 

Another issue that you might be facing with node.JS is the path...

Node.JS default path is in the NODE-Modules folder so it might not be looking for the folder in the same place your HTML file is .

It would be looking in the node-modules path in Node.Js

I faced the same issue when I first started using node . I eventually started making UML modules and using npm pack

THen i could just use requie('the module I want ')

Here is a tutorial on NPM Packages and how to create them

Hope this helps .

JonoJames
  • 864
  • 7
  • 18
  • While this shows the javascript file as status 200, it still doesn't run the function on the click. Moreso, it doesn't show any error in the console (probably because the HTML isn't calling anything). – Rhett Jarvis Jan 05 '20 at 05:21
  • I also had "console.log('test')" at the bottom of my js file which didn't display in the console, so I think it's not importing properly even though it received a 200 status – Rhett Jarvis Jan 05 '20 at 05:22
  • That is strange ... what happens if you npm pack it and install as a module... – JonoJames Jan 05 '20 at 05:24
  • The other thing you can do is give it a full physical path on the hard drive that is absolute – JonoJames Jan 05 '20 at 05:26
  • the direct path does not even load it, and returns an error message in the console. saying it failed to load script with physical path (I copy-pasted the js into documents (windows) and copied the path). If it affects anything, I'm operating off a USB right now. – Rhett Jarvis Jan 05 '20 at 05:35
  • Remove all the lines from js file. keep just console.log(test). check if are you getting that logged in console – Dev Ananth Jan 05 '20 at 05:40
  • in the console window type process.cwd(). this should throw the current working directory . – JonoJames Jan 05 '20 at 05:43
  • @DevAnanth It is logged, as another recommended, I'm checking the other functions now – Rhett Jarvis Jan 05 '20 at 05:44
  • Ok that means the node can see the file basicAlert() is probably just nested in another function or in an object.. – JonoJames Jan 05 '20 at 05:47
  • Then your file is loaded correctly. Add similar console log at the begining of every function. You can find after which function stopped working. – Dev Ananth Jan 05 '20 at 05:47
  • I think I've got it, but it's another problem tbh. I have two imports which looks like a no-no (Syntax Error: import declarations may only appear at top level of a module), I'll be looking more into those NPM packages Jono mentioned and modules. If you have any on-your-head answers for that, I'll gladly take them, but I know it's another problem altogether – Rhett Jarvis Jan 05 '20 at 05:57
  • Off the top of my head if you get your code into a module and install it with npm into your project . You can change the the imports to require and they will work as long as their definition have export.YourMethod(); . Also look up UMD or universal modeling Definition ....(https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm ) this allows you to create code that works with node or straight in the browser and with import without having to modify it when porting from node to the browser etc . – JonoJames Jan 05 '20 at 06:14
  • https://www.linkedin.com/pulse/why-javascript-making-waves-jonathan-james/ – JonoJames Jan 05 '20 at 06:24
  • You are a god. I'm wondering why mine wouldn't work with onclick but worked perfectly with an event listener, does onclick not work for images? – Shane.D Jan 16 '21 at 07:21
  • Nope the Tag has no onclick event in the DOM but you can add one through JS as shown above – JonoJames Jan 17 '21 at 05:51
-1

Share your html code. I highly doubt you made some mistakes in your html. It should work if you've written code as the following:

function basicAlert() {
 alert('Throw away!');
}
<!DOCTYPE html>
<html>
<head>
 <title></title>
</head>
<body>
 <button onclick="basicAlert()">Button</button>
 <script src="./js/throwaway.js"></script>
</body>
</html>
glinda93
  • 3,643
  • 2
  • 16
  • 39
-1

In your throwaway.js file just write console.log("invoking"); and if you are able to see this in console then your file is loading correctly.

If not you may need to check the js path.

Dev Ananth
  • 306
  • 1
  • 2
  • 8