Simple JQuery Script Does Not Work - javascript

I am trying to use jQuery for the first time and I am coding it by hand. But my jQuery code doesn't work at all... Here's my setup :
Index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="mainCSS.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="mainJQuery.js"></script>
</head>
<body>
<div class="test"> </div>
</body>
</html>
mainCSS.css
.test {
background-color:#FF0004;
border-radius:25px;
display:block;
height:500px;
width:500px;
}
mainJQuery.js
// JavaScript Document
$(document).ready(function() {
$('.test').click(function() {
$('.test').fadeOut('slow');
});
});

Just to state it for the record:
In order for your jQuery code to work, you need to link to the jQuery library in your HTML.
If you are following a tutorial that doesn't include this in the first step, you should find another tutorial to follow. If you got to this question because you did not follow the first step of your tutorial, you should read more carefully before falling back on StackOverflow, or risk getting some serious downvotes.
The two most common ways of including jQuery in your HTML page are:
1) Downloading the library, and linking to a local copy. In your <head> section:
<script type="text/javascript" src="/url/path/to/local/jquery.min.js"></script>
2) Linking to a remote copy of the jQuery on Google's CDN. Again, in <head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
If you don't link to jQuery using one of those options, or something similar, your code will not work. In most browsers you will be able to tell that this is the problem by opening the Javascript console, typing "jQuery" and getting an error like jQuery is not defined.
It's amazing that I couldn't find a duplicate question to close this in favor of, but then again I didn't click on every single "Why doesn't this simple jQuery script work" question on StackOverflow.
And there are a lot.

Related

Make an animation with the Glorious JavaScript library

I have been trying to use the library to make material for my students.
https://glorious.codes/demo
I want to make animations, but I cannot understand how to use or where to use the library. I think it is necessary to use it from an html file. install the library but when opening the page it only creates the text that I place as a test.
I am using WebStorm as IDE, creating a node.js project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="node_modules/#glorious/demo/dist/gdemo.min.css">
<script src="node_modules/#glorious/demo/dist/gdemo.min.js"></script>
</head>
<body>
</body>
</html>
Can someone guide me on what program or how to work with the library. It is the first time that I try to perform animation with JavaScript.
If you are new to web technologies, there is a pretty steep curve here. Personally, I'd take a step back and familiarize myself with the tools. If you have a minute, check out W3school's site. There is plenty of information to get you moving quickly with HTML/CSS/JS. Specifically focus on CSS selectors and Javascript and this will make a lot more sense.
Now for the question you asked:
First, NodeJS isn't necessarily required to achieve your goal. You can create a simple HTML file and reference the Glorious libraries directly from the web. See what I did in the <script> and <link> elements below.
Once you have the libraries loaded, you need to:
Instantiate the library and assign it to a variable to use in the future (see const demo = new GDemo(...))
Tell the library where in your HTML you want it to render the animation. In this case it is a <div/> with id='container'.
Tell the library what to render. This is the gDemo.openApp(...) section. I pulled this example directly from this library's GitHub page.
const gdemo = new GDemo('#container');
const code = 'console.log("Hello World!");'
gdemo
.openApp('editor', {
minHeight: '400px',
windowTitle: 'demo.js'
})
.write(code, {
onCompleteDelay: 2000
})
.openApp('terminal', {
minHeight: '400px',
promptString: '$'
})
.command('node ./demo')
.respond('Hello World!')
.command('')
.end();
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.jsdelivr.net/npm/#glorious/demo/dist/gdemo.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/#glorious/demo/dist/gdemo.min.css" rel="stylesheet" />
</head>
<body>
<div id="container"></div>
</body>
</html>
Could you please detail a bit more the problem. From your example you just created an empty page. What are you trying to put in your page ? Tables ?
Also I would suggest the use of framework like Materials (https://material.io/components) within React if you are starting a Js project from scratch except if you have something specific in this lib you really want to display.

Accessing jQuery within a JavaScript namespace / module pattern [duplicate]

So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it's because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc... so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I'm sure my problem here is equally as simple, but over an hour of hunting, still no luck...
Edit: Additional information...
The solution file (which I've recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I'm doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
It's states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here's how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder 'scripts'.
Finally, the error is gone and what a relief!
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
...to this...
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">\x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
Anover variant, in my case - I was forced to use proxy. So - IE11--> InternetOptions --> Connections-->LANSettings-Proxy Server--> UseProxyServer - should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 - -just like in top example
I was getting this same error code:
(Error: 'generateText' is undefined)
...on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn't hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??

How to display variables from external JavaScript in HTML. Internet Explorer 7

I realize this is a horribly newbie question, but Ive been trying to fix it for days trying different methods so I just wanted to ask what would you do.
I am attempting to create a web program to use at work, and I have this setup:
Windows 7
IE 7 - Cannot Upgrade.
The "website" is not a webhost, basicly I have a folder on my desktop with html/css/js files and I use IE to run the scripts, no host.
I want to keep a set of vars, mostly strings, in an external JS file and pull the JS into different HTML pages. I want it to write on load of the document.. not on ready. It does not have to be user dynamtic.
Also, When I make the js file, does it have to have a header.. like HTML has doctypes?
I really appreciate your help as I am trying to learn and will cont on my own from here. My setup is much different than most, and im not sure which part was causing my problem so I finally broke down and posted.
When you write your JavaScript file it doesn't have to have any header or doctype. For example you can have a variables.js file that looks just like this:
var x = "abc";
var y = "def";
and have many HTML files that include variables.js like this:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<!-- page content -->
<script src="variables.js"></script>
<script>
alert(x);
</script>
</body>
</html>
and your variables should be available there. Any script that is included after the reference to your variables.js should have access to everything that was included before without the need to listen to any events.
If you need to listen to the events then I suggest to use jQuery or some other JavaScript framework. An example for jQuery would be:
$(window).load(function() {
alert(x);
});
A more advanced example of changing the DOM elements:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<p>Select variable:</p>
<p>
Show x
Show y
</p>
<p>Value:</p>
<p id="value"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="variables.js"></script>
<script>
$('#show-x').click(function (e) {
e.preventDefault();
$('#value').html(x);
});
$('#show-y').click(function (e) {
e.preventDefault();
$('#value').html(y);
});
</script>
</body>
</html>
If it's not a global variable, you can't display/print/access or whatever you call it because it has a local scope, defined in a function.
You can probably only use a debugger simply to debug it

JavaScript runtime error: '$' is undefined

So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it's because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc... so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I'm sure my problem here is equally as simple, but over an hour of hunting, still no luck...
Edit: Additional information...
The solution file (which I've recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I'm doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
It's states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here's how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder 'scripts'.
Finally, the error is gone and what a relief!
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
...to this...
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">\x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
Anover variant, in my case - I was forced to use proxy. So - IE11--> InternetOptions --> Connections-->LANSettings-Proxy Server--> UseProxyServer - should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 - -just like in top example
I was getting this same error code:
(Error: 'generateText' is undefined)
...on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn't hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??

My first dig at jQuery

I'm a complete newbie as far as jQuery is concerned. I also don't know much of JavaScript except for some very basic stuff.
I'm following this tutorial here: http://docs.jquery.com/How_jQuery_Works
And nothing's working! :-)
I created a folder on my machine's hard drive here: C:\rnd\jQuery
Then, in that folder, I put the jquery.x.x.js file that I downloaded from the jQuery website and I created a test.html file and wrote the following code in it:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; }
</style>
<script type="text/javascript">
$.(document).ready(function() {
$("a").addClass("test");
$("a").click(function(event) {
alert("Thanks for visiting.");
event.preventDefault();
});
});
</script>
</head>
<body>
jQuery
</body>
</html>
It just does the normal behavior of taking me to the jQuery website. I ran it on Chrome, IE and Firefox. I have JavaScript enabled in the browsers. It's all the same everywhere. It doesn't do anything that I expected it to do. It just takes me to the website.
Except on IE, it shows me that message box saying an error occurred in your script. When I click "Yes" to debug, it opens up the debugger but it doesn't highlight any line of code so I don't really know what's happening.
Then, when I had the following line to my code:
$("a").hide("slow");
And my complete code looks like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; }
</style>
<script type="text/javascript">
$.(document).ready(function() {
$("a").addClass("test");
$("a").click(function(event) {
alert("Thanks for visiting.");
event.preventDefault();
$("a").hide("slow");
});
});
</script>
</head>
<body>
jQuery
</body>
</html>
At this, nothing different happens in Firefox and Chrome, but in IE, it breaks again into the debugger, this time with this line highlighted in yellow, and it reports that the identifier jQuery is not defined.
(function($) {
$.fn.textDropShadow = function(){
$(this).html('<span class="jq-shadow">'+$(this).html()+'</span><span>'+$(this).html()+'</span>');
return $(this);
}
})(jQuery);
And that, I believe is some JavaScript code on the jQuery website.
I feel completely lost. Any help would be appreciated.
Update:
I have my complete HTML and it is valid XHTML. It's too bad the browser displays that as an HTML response stream and I can't even get it to show up here as a script. Damn! How do you make HTML show up here?
I can see one issue. You have a . following the $ in the document ready statement.
$.(document).ready(function()
^--- remove the .!
It should look like this:
$(document).ready(function()
First off make sure you have the jQuery library referenced before writing any jQuery code (or loading any plugins)
<script type="text/javascript" src="{path to jquery.x.x.js}" ></script>
Also, it should be $(document).ready(function() { });
not $.(document)
Obviously the problem was an extra dot in the $.document part however here is a tip for you when learning jquery.
You may find yourself in the situation that you have another javascript library running on the page and it's using the $ symbol too. A good way to keep your jquery separate from the other library but still share the $ symbol is to alias $ inside your jquery init statement.. like so.
// the dollar symbol doesn't exist outside of this as we started it with jQuery so i personally like this approach.
jQuery(document).ready(function($) {
$('#...');
});
Did you include the line:
<script type="text/javascript" src="jquery.js"></script>
You need to show more of your page for us to know what's wrong.

Categories

Resources