How do I reference jQuery from my HTML/JavaScript application? - javascript

I keep getting Uncaught ReferenceError: $ is not defined error.
I assume everything is ok and working. My JQuery code is inside my Javascript file. I assume that isn't how it works? Should I have a JQuery file?
I have this inside the head of my HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
This is my Javascript file:
function typing(id, sentence){
var result = $.Deferred();
var index=0;
var intObject= setInterval(function() {
document.getElementById(id).innerHTML+=sentence[index];
index++;
if(index==sentence.length){
clearInterval(intObject);
}
}, 100);
return result.promise();
}
var sleep = function(ms) {
var result = $.Deferred();
setTimeout(result.resolve, ms);
return result.promise();
};
typing('container','Subject Name:').then(function() {
return sleep(500);
}).then(function() {
return typing('container',' Carlos Miguel Fernando')
});
Where did I go wrong?

Your question is fairly unclear, but essentially, you just have to make sure jQuery is loaded before your code. So for instance:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
or
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
// Your code
</script>
But not
<!-- Not like this -->
<script src="your-code.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Note the order of tags.
These tags do not need to be in the head, and in fact, putting them there is not best practice. They must be in head or body. Best practice barring a specific reason to do something else is to put them at the very end of body, e.g.:
<!-- site content here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
</body>
</html>

Related

Function not working if src is a variable?

With this HTML the function myFunc() can be executed. https://myurl.de/myjs.js has the function myFunc in it.
<head>
<script type="text/javascript" src="https://myurl.de/myjs.js"></script>
<body>
<script type="text/javascript">
myFunc();
</script>
</body>
</head>
But with the second HTML I get an Error: Uncaught ReferenceError: myFunc is not defined.
https://myurl.de/settingsFile.js is a file that includes this url in a var: https://myurl.de/myjs.js so basically SettingsFile.UrlToMyJS is this https://myurl.de/myjs.js
<head>
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript" id="myid"></script>
</head>
<body>
<script type="text/javascript">
document.getElementById('myid').src = SettingsFile.UrlToMyJS;
myFunc();
</script>
</body>
When I console.log(document.getElementById('myid')) this is the output:
<script type="text/javascript" id="myid" src="https://myurl.de/myjs.js></script> which is correct. It looks exactly like the script in the head of the first html (with the difference that it has the id="myid").
Yet it does not work. Why and how can I fix it?
settingsFile.js:
var defaultURL = 'https://myurl.de/';
var SettingsFile = {
UrlToMyJS : defaultURL + 'myjs.js',
}
The reason it's not working is that you can't add a src to a script element that's already in the DOM — or rather, doing so doesn't do anything. The script element has already been processed.
Instead, create it and then append it:
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
That waits for the script to load, then calls myFunc (which should exist by then).
Also note that as I and Jeremy pointed out in the comments, body doesn't go in head, it goes after. It's also generally best to put script tags at the end of body (if you're not using async or defer attributes on them or type="module"). So in all, something like:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
var script = document.createElement("script");
script.onload = function() {
myFunc();
};
script.src = SettingsFile.UrlToMyJS;
document.head.appendChild(script);
// If you need to support IE8, use the following instead of the previous line:
//document.getElementsByTagName("head")[0].appendChild(script);
</script>
</body>
Another option is to use document.write. This sort of thing may be the last at-least-partially appropriate use of document.write during the main parsing of the page:
<head>
<!-- head stuff here -->
</head>
<body>
<!-- content here -->
<script src="https://myurl.de/settingsFile.js"></script>
<script type="text/javascript">
document.write('<script src="' + SettingsFile.UrlToMyJS + '"><\/script>');
</script>
<script>
myFunc();
</script>
</body>
You can try creating a element and then appending it to your title
For Example (script code) :
var script = document.createElement("script");
script.src = "YOUR_SCRIPT_SRC_HERE";
document.getElementsByTagName('head')[0].appendChild(script);
Here I am creating a new tag in html and then appending it to the head of your html. Even as T.J. Crowder mentioned in the comment try removing your body from the head

How would I reference exif.js in a Javascript file as I can't use getExif?

I am trying to use exif.js on my HTML page, but I don't think I'm referencing the exif.js file correctly, as window.onload = getExif returns an error saying it's undefined.
I have tried adding <script src="exif.js type="text/javascript"></script> to my HTML file and referencing my other file with <script src="myscript.js" type="text/javascript"></script> as well. It still doesn't seem to be working.
HTML:
<html>
<head>
<script src="exif.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript"></script>
</head>
<body>
<img src="myimage.png" alt="" id="image">
<div>
<span id="metadata"></span>
</div>
</body>
</html>
Javascript:
window.onload = getExif;
img = document.getElementById("image")
EXIF.getData(img, function() {
var allMetaData = EXIF.pretty(this);
var allMetaDataSpan = document.getElementById("metadata");
allMetaDataSpan.innerHTML = JSON.stringify(allMetaData,null, "\t");
});
The error I got was Uncaught ReferenceError: getExif is not defined. I'm not sure if I'm doing something wrong or not because everything looks good to me. Any help would be greatly appreciated.
You have no function named getExif defined. It's not something special exported or defined by exif.js, but simply a pattern they were following in the documentation examples. I imagine what you were going for is:
window.onload = getExif;
function getExif() {
var img = document.getElementById("image");
EXIF.getData(img, function() {
var allMetaData = EXIF.pretty(this);
var allMetaDataSpan = document.getElementById("metadata");
allMetaDataSpan.innerHTML = JSON.stringify(allMetaData,null, "\t");
});
}

How to load different html files in QUnit?

I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}

Issue with wisdom generator

I am trying to display random wisdom on a web page but I cannot figure out why the code below does not work.
Thank you
My javascript external file is:
function random(low, high) {
return Math.floor(Math.random()*(high-low+1)) + low;}
function randomarr() {
var arr = new Array("...1", "...2", "...3");
return arr[random(0, arr.length-1)];}
function display(){
var k = randomarr();
alert(k);}
and my html file
In the head section I've got:
<script type="text/javascript">
src="java.js"
</script>
And in the body section I've got:
<p>
<script type="text/javascript">
document.write(display());
</script>
</p>
The syntax for including the script in the <head> is wrong. Try this:
<script type="text/javascript" src="java.js"></script>

external JS does not work

I have the following code:
<script language="javascript" type="text/javascript">
$.fn.dataTableExt.oPagination.input = {
"fnInit": function (oSettings, nPaging, fnCallbackDraw) {
....
},
"fnUpdate": function (oSettings, fnCallbackDraw) {
....
}
};
</script>
and it works, but when I create external file and put this code inside this file (of course without <script></script> ) - it does not work. Why?
just make sure the jQuery is the first script you load
<script type="text/javascript" src="jquery.js"><scrip>
<script type="text/javascript" src="yourScript.js"><script>

Categories