jQuery "$ is not a function" error - javascript

I swear I have included jquery in the page header, it is right there!
Nonetheless the following code, which I've included near the bottom of the page (and inline for now) gives me an error saying "TypeError: $ is not a function."
<script>
function displayResult(longA, latA, longB, latB, units) {
$("#distance").html(calcDist(longA, latA, longB, latB, units));
if (units=="m") {
$("#unitLabel").html("miles");
$("units").prop("selectedIndex",0);
} else {
$("#unitLabel").html("kilometers");
$("#units").prop("selectedIndex",1);
}
$("#longA").val(longA);
$("#latA").val(latA);
$("#longB").val(longB);
$("#latB").val(latB);
}
$("#calculateButton").click(function() { //This is the line it's complaining about
var longA=$("#longA").val();
var latA=$("#latA").val();
var longB=$("#longB").val();
var latB=$("#latB").val();
var units=$("#units").val();
displayResult(longA, latA, longB, latB, units);
})(jQuery);
</script>
Higher up in the page header I've got the following:
<script src="jquery.js" ></script>
<script src="calcDistSinglePage.js" ></script>
I'm not using Wordpress or anything, this is a very straightforward hand-coded HTML page.

Try wrapping your code in a closure (which is considered good practice anyways):
(function($) {
$("#calculateButton").click(function() {
// do stuff...
});
}(jQuery));
If this snippet still complains with the same error, there's bound to be a problem with the way you're loading the jQuery library.
Also, make sure that you don't overwrite the $ variable in your other code. For example, inside calcDistSinglePage.js.
The dollar-sign is a very straight-forward javascript variable and can be reassigned to whatever you want. According to the error, $ currently is something but not a function (otherwise you'd receive a ReferenceError stating that $ is undefined). So probably, somewhere in your code, you've overwritten it.

Make sure the jQuery library it's the first script you load.
Add this just before the closing </body> tag.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-{{JQUERY_VERSION}}.min.js"><\/script>')</script>
Download the file locally and inside js/vendor/ add the file.
Replace the value {{JQUERY_VERSION}} in the script above adding your jquery version.
Here one CDN you could use.
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js
https://code.jquery.com/jquery-2.1.3.min.js

You are probably linking it from a root folder that is not your HTML folder. Use an absolute path:
<script src="/jquery.js" ></script>
Or make sure jquery.js is in the same folder as your HTML.

Related

make javascript module global?

I am trying to execute a function from within a script. It shows no error but also doesnt execute the function.
file.mjs
function test() {
console.log("test")
}
This is my html:
index.html
<head>
<script type="module" src="file.mjs">
</head>
<body>
<button type="button" id="Submit">Submit</button>
<script>
document.getElementById('Submit').addEventListener('click', test);
</script>
</body>
This worked fine using 2 separate scripts, to make it global I was using type="text/javascript".
But since my file.mjs is actually importing a library I had to set it as type="module" and the function wont execute. Is there a way to make the module scope global?
Before I go on, there's a big problem that needs addressing:
Your syntax is wrong. If you want to import a script, that tag must have the src attribute and nothing within the tag. If you want to execute an "inline" script, it should NOT have the src attribute, so what you should have is two script tags, one to import the module, the other to execute your inline code.
Now, I'm not sure what you mean by "global". To obtain true "globalness", you would have to define your variable in the global object (window or globalThis) like so:
// file.mjs
function test() { ... }
window["test"] = test;
Then in your regular script you could just do document.getElementById('Submit').addEventListener('click', test);.
That sort of completely destroys the purpose of JS modules though, as it's supposed to be an "import/export" model.
Ignoring the "global" part of your question: if you want to use modules for what they're worth, you would be importing and exporting them, and you would only (almost always) link a <script type="module"> in your HTML if it only imports and never exports (exporting would be useless). The reason you need type="module" is to tell the browser that you're operating on modules so it'll allow you to import/export. With that said, your code would look like this:
// file.mjs
export function test() { ... }
And in your HTML, you would only need one script tag (that goes right before the ending body tag):
<script type="module">
import { test } from "/path/to/file.mjs";
document.getElementById('Submit').addEventListener('click', test);
</script>
I hope that clears it up for you, and docs if you need them.

jQuery not working in html file (JS LINT errors such as '$' was used before it was defined)

I am using HTML, CSS, and JS. I am trying to use the JQuery library but it is not being recognized by my html file. I am inserting it above my external .js file, so I don't think that is the issue. Here is what is in my HTML file:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
This is what is in my JS file:
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() > 970) {
$('.navbar').addClass('navbar-fixed-top');
}
});
});
My code editor is throwing errors when I save this js file because of errors like:
-'$' was used before it was defined.
-Expected exactly one space between 'fucntion and '('
Anyone know what the issue might be? Thanks in advance.
This might not be the issue, but you may wish to attempt to load the jquery file by HTTPS (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js), especially if you are running your site on an HTTPS connection.
Otherwise, it seems to work when I test it:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() > 970) {
$('.navbar').addClass('navbar-fixed-top');
}
});
console.log("done!")
});
</script>
The problem is in your <script> tag, as #B.Fleming said maybe the HTTPS protocol. This tag is working:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
put this in top of your code where you are using jQuery
/* global $ */
alternativ is prefixing it with window
I don't like using the global $ sign cuz other libs are using it as well. what i usably dose is getting the $ from the closure function like this
jQuery(function($){
// document is ready, You may use jquery here and now
$('body')
})
and to get away with jQuery is not defined use window.jQuery instead
ps, always load stuff from https when possible

jQuery $ is not a function

I have a problem including a jQuery script in my webpage. I always get the error "$ is not a function" in line 6. I reduced my script to the following very simple one:
$(document).ready(function(){
myTest();
});
function myTest(){
window.console && console.log($("#test"));
}
Why is there an error in line 6? Why not already in line 1?
You have not included jquery.js in your page, or the path you have used is incorrect. Here is an example one using Google's CDN:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
// your code here...
</script>
</head>
</html>
The line numbers given in browser error messages are notoriously unreliable, always use the actual error message as a guide to the problem.
Hi Please download and include jquery.js or jquery.min.js
in script tag
Give jquery.js path in script src attribute
This error message means that jQuery is not included

Synchronous external JS loading with zombie.js

The problem:
I'm using zombie.js to test my client-side javascript, but I am running into a problem. Zombie.js does not provide synchronous <script> tag execution, and, in fact seems to not execute external JS files at all. A basic test confirms this:
<script type="text/javascript" src="test1.js"></script>
<script type="text/javascript" src="test2.js"></script>
<script type="text/javascript" src="test3.js"></script>
<script type="text/javascript">
console.log("Inline javascript.");
</script>
Each test#.js contains a single line: console.log("TEST#.JS");
When I render this in a regular browser, the console displays the expected:
TEST1.JS
TEST2.JS
TEST3.JS
Inline javascript.
But when I run it with zombie.js, I only see a single line Inline javascript.
Here's what I have tried to get around the issue:
using document.createElement to dynamically append a script tag to the document
using document.write to add the script block into the html
using a setTimeout on console.log("Inline javascript") in combination with 1 and 2 to give the test scripts some time to load.
Is there any way to resolve this issue, besides placing the JS code from all my external JS files into a huge <script> block?
Are you sure the browser object has the "runScripts" option set to true? If not you can use the following syntax:
browser.visit('... your page url ...', { runScripts: true }, function (e, b) {
console.log('executing callback');
});

why jquery/javascript code get conflict with other jquery/javascript?

While using jquery or javascript code most of the time i have to face the problem of jquery or javascript conflict.
Still i haven't got the reason why this stuff get conflict with other code?
Any one have any idea about this?
And any solution so that next time this issue will not occur while project development.
I have one solution to stop the conflict of jquery files that is,
<script>
var j$=jQuery.noConflict();
</script>
but all the time this code is not working.
If you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery. In order to avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page.
Method 1:
When you put jQuery into no-conflict mode, you have the option of assigning a variable name to replace $. ( only once )
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>var $j = jQuery.noConflict();</script>
Method 2
You can continue to use the standard $ by wrapping your code in a
self-executing anonymous function; this is a standard pattern for
plugin authoring, where the author cannot know whether another library
will have taken over the $.
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
(function($) {
// your code here, using the $
})(jQuery);
</script>
Method 3:
use jQuery instead of $
there few other ways to do so
reference
For jQuery, it's explained in noConflict's API page; basically, many JS frameworks use $ as a function name, and so they may conflict if more than one is used. Which it shouldn't anyway.
Try placing this in your header:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"> </script>
Try to give an alert when DOM is ready and find it alerts or not if not there is a conflict
<script>
$(document).ready(function () {
alert("Hello!");
});
</script>
I there is conflict try this:
<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>

Categories

Resources