Issue running function from external js file - javascript

I am trying to do something which I feel should be elementary and basic but it is not working. I have looked at many related Stackoverflow QAs but none covers this exact issue.
I want to run a function from an external js file called main.js. The file is loaded at the bottom of the body section of an html page in the usual way. All contents of the file is within the standard jQuery wrappers. I know it is loading properly because I can see it in Developer Tools and various animations coded in it are running correctly. I have jQuery 3.3.1 loaded in the head section of the page and again it must be loading properly because the animations are working.
As a test I have the following function in main.js:
function alerttest() {
alert('Function test works');
}
Then in the main body of the html page I call the function as follows:
<script>
alerttest();
</script>
So when I refresh the page I should get an alert but this does not happen. I get an error in the console:
Uncaught ReferenceError: alerttest is not defined.
This would happen if I loaded scripts in the wrong location so I also tried this to call the function so the DOM would be loaded first:
<script>
$(function() {
alerttest();
});
</script>
but I get the same Reference error. Can anyone suggest what is going on?
Environment: Windows 10, VSCode, Codeigniter 3, jQuery 3.3.1, WAMP with PHP 7.4.7

I believe I have solved the problem and, as I suspected, it was about the location of scripts. I have always been advised to include scripts at the bottom of the page just above the closing body tag but this didn't work in this instance. I have now located my main.js in the head section along with the jQuery CDN and everything works just fine.
Many thanks for responding.

Related

JS file is loaded but not being executed

I have a project running on Symfony with angular js and its all working good except for a strange thing.
I added a JavaScript file to execute some JQuery functions i already tested in the browser console and they are all working good with no errors the problem is when I inspect element i can see the file being called in the head and i can also see it in the sources I can even open the link and see the file.
But for some reason the functions in there are not being called executed.
following the images to prove that its loading with no errors.
Edit:
Its not about putting the code in ready function or not
$(document).ready is firing before angular has loaded the content onto the page.
So it might be the possibility of your jQuery plugin calls before your Angular loads the content onto the page.
what you need to do is somehow, call your jQuery plugin once your Angular gets init or you can turns your code into directive.
My script file was also loading but not executing but I had a different issue, basically avoid using href attribute in script tag and instead use src

basic javascript alert not working in Intel XDK code editor

I'm starting fresh with a new blank Intel project and I haven't even started coding yet. I'm just setting up my file tree and making sure the html and javascript pages are connected via the right anchors and script paths. My first .js file won't work though.
I've included a screen shot of test code and the errors. I know the syntax is correct because it works when I put it in <script> tags in the index.html file.
I'm getting "document not defined" and "alert not defined" errors or the js page though. I don't know what that means.
I've considered that my script tag src path in the index file is incorrect, but all the paths are relative in the commented out template script tags intel provides on the index page right out of the box, so why would I have to use an absolute path?
My path is: js/Test.js and it's the last script tag before the body.
Index.html file
*****UPDATE****
So I've tried a few things and it's still not working but I HAVE managed to get my errors down to just one inexplicable "missing semicolon", which will turn into an "unnecessary semicolon" error if I place it.
Any way as per the first screen shot you'll see that I wasn't placing the document object inside of an explicitly declared variable. Once I did that and accessed it through dot syntax instead of an equal sign then I stopped getting the error. I included this screenshot to show my work before I made the changes.
so the problem I went on to have is that unless every function or dom object was declared with "Var", I'd get an error. This includes the alert() function which I don't think I've ever seen needing to be declared that way, but I gave the code editor what it wanted and this last screenshot is the results. It's not working, BUT I'm not getting the errors I was before, except for the missing/unnecessary semicolon paradox. Removing it or including it throws an error.
JavaScript can be loaded before or after the HTML, however the way it is done is slightly different depending on how you do it.
For example if you wish to include your JavaScript files within the head of the HTML file then you must wrap your JavaScript code with either DOMContentLoaded or jQuery's $(document).ready().
The common misconception of using window.onload will not fix the issue where the elements have not loaded in correctly.
The Mozilla Developer Network states on this page:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event - load - should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
That quote in itself should prove that onload should not be relied on if you want the full DOM to be loaded properly before you start manipulating it. Instead you should do the following:
Vanilla
document.addEventListener("DOMContentLoaded", function (e) {
/** DOM has been fully loaded here, so manipulation can begin. **/
/** Your code here. **/
});
jQuery
$(document).ready(function () {
/** DOM has been fully loaded here, so manipulation can begin. **/
/** Your code here. **/
});
Click this link to see the difference between vanilla and jQuery.
The second way you can load JavaScript is by having all the script tags within the body but after all the HTML, that way it is guaranteed to load after the HTML.
Example
Try this working example I quickly coded up.
HTML
Replace the content within the body tag of your HTML to the following:
<button id="myJsTest">Click Me!</button>
<div id="clickCounter">Click Count: 0</div>
Replace the contents of your JavaScript with the following:
JavaScript
document.addEventListener("DOMContentLoaded", function() {
var clickCount = 0;
document.getElementById("myJsTest").addEventListener("click", function() {
clickCount++;
document.getElementById("clickCounter").innerText = "Click Count: " + clickCount;
});
});
Then use the Emulate tab in Intel XDK to test it.
Additional Information
When I use Intel XDK and I have an error, I quickly load the file in to the browser and check the console. It can be a really helpful and effective way of squashing those pesky little bugs.
Try using window.alert as alert is defined in the window object.
The reason you're seeing all those "error" messages in the editor window is because you've got the various JSLint/Hint tools loaded in the editor. They're trying to keep you honest and save you lots of time in the debugger chasing potential syntax errors.
The editor inside the XDK is Brackets, it is using standard Brackets extensions to provide those JSLint/Hint tools. You can download it and run it standalone on your system and edit directly within it, you don't have to use the editor inside the XDK (or you can use any other editor you like).
Because the Lint/Hint tools only look at one file at a time, and because your app is normally spread over multiple files, they don't know much about about what's defined in your other files. Likewise, those hint/lint tools need to be told that you're using some of the standard global methods and properties that are expected to be found in a browser (but which may not be found in other JavaScript environments, because JavaScript is no longer limited to just a browser environment -- in fact, your XDK app, aka Cordova app, runs inside a "webview" not in a browser, but that's another story...)
So, you should follow some standard practice of setting up your JSHint/Lint directives at the top of your JS files. For example, this is a good starting point:
/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false */
See the JSHint documentation for details... and see the "Blank Cordova Starter App" in the "Start a New Project" section of the Projects tab for a better blank template to start (there is no real difference between a blank template and a demo app, they are structured identically).
For a more complete and even more instructive app, see the "Hello, Cordova" sample app. Both of those apps can also be found on the Intel XDK GitHub repo.
You are adding the js file that is <script src="js/Test.js"></script> inside header tag.
So js will be first loaded and and it will attach all events to it. But when js is loaded button id="jsTest" is not present because DOM is not loaded.
Solutions :-You can follow either of the approach
Add your js files after DOM is ready
<body>
<button id ="js/Test.js">Test JS</button>
// other HTML tags
<script src = "js/Test.js></script>
</body>
Use window.onload
The load event fires at the end of the document loading process.
window.onload = testJsFile(){
//Your code goes here
}
I will prefer to use the first approach since that also address other issues like page loading time
Try to put the line outside your JS function
document.getElementById(......
inside your html page between
<script>HERE</script>
If this is still no working. Try to add onClick attribute to the button like this:
<button id="" onClick="testJsFile()">
Its also good to use google chrome element inspection while devlopping cuse it will give you error msg for all these things.

Head js Problems with loading javascript files

I'm using Head js to load my javascript files in parallel. I added head js to my head and then used head.js("path/to/file/my.js"); but when I load my webpage the script is missing. Only after refreshing a few times does the whole script work properly. Why do I need to refresh it to make it work? Any suggestions would be appreciated!
As the scripts are loaded asynchronously, you can't use it immediately. After you have refreshed the page, it will find the script in the cache, so it will load in time for any code needing it sometimes.
Use the ready method for any code that needs the script:
head.ready(function() {
// any code that needs the script to be loaded first
});
Another way is to mark your library and then get the ready event when your script is loaded. Read more from http://headjs.com/ Labeling scripts.
head.ready("your", function() {
});
head.js(
{jquery: "http://http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"},
{tools: "http://cnd.jquerytools.org/1.2.5/tiny/jquery.tools.min"},
{your: "http://a.heavy.library/we/dont/want/to/wait/for.js"},
// label is optional
"http://can.be.mixed/with/unlabeled/files.js"
);

jQuery tabs is loaded but not working in WordPress

I am trying to work with jQuery UI tabs in WordPress but I keep getting the "jQuery("#").tabs is not a function" error.
I thought the tabs file might not be loading but looking in firebug it shows it is loading. I am also using modernizr so I thought there might be a conflict with that but using jQuery.noConflict(); did not solve the problem either. At first I used to load jQuery but for some reason it wouldn't work. Now I just linking directly to the files and they are loading.
If it helps, I am trying to get tabs working for this tutorial. The website I working on is lbk.newcoastmedia.com/wordpress
Thanks for any help!
I see the following scripts being loaded on your page:
modernizr-1.6.min.js
l10n.js
jquery.js
galleria.js
and
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 4000);
});
</script>
$.tabs is an extension of jQuery UI, and I don't see jQuery UI or the tabs extension loaded on your page. Look at the very bottom of the source at your link and you'll see the following two scripts, which I believe are what you're missing.
ui.core.js
ui.tabs.js
Your debugger is alerting you that $.tabs is not a method because it really hasn't been defined yet.
Just had this problem on Drupal and resolved it by downloading a custom build of the jQuery UI library WITH Tabs selected. Apparently the default jQuery UI library that shipped with Drupal didn't have this module, so perhaps this is also the case with WP.

Why would javascript work embedded in html page, but not in external script?

I am using a simple script, and when the script is embedded into the actual html page it works just fine, but when it is thrown into an external .js the script no longer works, i am not seeing any errors in the console, it is a jquery delegate function, and i know that the external script is working, because there are other scripts in it that are currently working just fine.
just wondering if there is a cause to this problem, or if anyone else has encountered this.
If you're embedding the script in the body of the HTML document, and if your script relies on the existance of elements before the script in the body, then that same script wouldn't work if loaded as an external resource since that code would be executed before the HTML DOM is built.
To make sure your scripts work in either case, wrap any startup code in a $(document).ready(...) method.

Categories

Resources