I was wondering how to make the Jquery library work. I have of course research on this before asking this question, and I have a book that suggest doing the following:
<script src="scripts/jquery-1.6.2.min.js"><script>
however, for some reason, the stuff on my page does not respond to my code even with this. So I was very confused. What I tried was, moving the files I was working on to the same directory as the jquery-1.6.2.min.js, since jquery is a js library, but didnt work. I was wondering what could it be? I have search for syntax errors like mad, so I reallllllyyyy doubt thats the problem. I was wondering what I did wrong? The only other option I can think of is using the website tag (which I havnt tried yet):
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
or
<head>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery- 1.6.2.min.js"></script>
</head>
Which I wanted to avoid because I didnt want to rely of being on the web when I do my work, we never know... Thanks!
This is the full code by the way:
<!DOCTYPE html>
<html>
<head>
<title>jQuery goes to DOM-ville</title>
<style>
#change_me {
position: absolute;
top: 100px;
left: 400px;
font: 24px arial;
}
#move_up #move_down #color #disappear { padding: 5px; }
</style>
<script src="scripts/jquery-1.6.2.min.js"></script>
</head>
<body>
<button id="move_up">Move Up</button>
<button id="move_down">Move Down</button>
<button id="color">Change Color</button>
<button id="disappear">Disappear/Re-appear</button>
<div id="change_me">Make Me Do Stuff!</div>
<script>
$(document).ready(function() {
$("#move_up").click( function() {
$("#change_me").animate({top:30},200);
});//end move_up
$("#move_down").click( function() {
$("#chage_me").animate({top:500},2000);
});//end move_down
$("#color").click( function() {
$("#change_me").css("color", "purple");
});//end color
$("disappear").click( function(){
$("#change_me").toggle("slow");
});//end disappear
});//end doc ready
</script>
</body>
</html>
The problem is most likely the path... Are you just using HTML pages? If so, there are a couple of things to note:
1.) When a path begins with a / it means it starts at the root folder.
2.) When a path does not start with a / it means its going to start relative to the current folder it is in.
To fix:
Inside the folder with your html, make a javascripts folder (you could call it anything, "js" for example), and place your jquery javascript files within it.
Then use this for the path to jquery:
<script type="text/javascript" src="/javascripts/jquery.min.js"
This will reference the absolute path, so if later on, you have html files in nested folders, it won't look to the relative path but the absolute one.
As well if you want to use the google version when you have internet, and a local version when you don't you can use this snippet:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script type="text/javascript">
window.jQuery || document.write("<script src='/PATH/TO/jquery.js'><\/script>")
</script>
Addendum:
Fixed the post to reflect Fabrício Matté correction.
The absolute path can get a bit funky if you're not running behind a webserver (apache for example). This is why it would work on a server, and not on your computer.
If you're running it locally, without a webserver (don't do this, install MAMP or XAMP, Apache, nginx, IIS, anything...), you'll need to specify the full path:
Mac:
/Users/yourusername/Sites/website/index.html
PC:
C:/somethign/something/else/index.html
Do you have your page (the one you copied all code for and showed us) in the same directory as a directory called "scripts"? In that "scripts" directory, do you have a file called "jquery-1.6.2.min.js"?
My guess is one of three things is happening:
You're jquery file is in a different directory
You never included the jquery file
the jquery file name is not exactly the same
If you check in FireBug, I'll bet that this file is missing
Related
I've been following this article (https://dev.to/programliftoff/create-a-basic-webpage-with-css-and-javascript--104i) to get started on building an interactive webpage, but I can't get the JS and CSS to work.
I'm working in Sublime, and I followed this tutorial (https://www.youtube.com/watch?v=oqD5C77Tk3I&feature=youtu.be) to run it through http rather than the file system.
I've double checked the folder paths fifty times (they're just saved on my desktop as 'scripts' and 'styles' in the same folder as my index.html doc), and tried different variations of dots at the start of the paths and slashes both ways, but the JS and CSS just won't load. I've also moved the 'link rel' and 'scripts async src' lines between the head and body tags, but it doesn't seem to make a difference.
My html doc looks like this,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Website</title>
<link rel=“stylesheet” type="text/css" href=“../styles/styles.css” />
<script async src="./scripts/index.js"></script>
</head>
<body>
<h1>Hello, World</h1>
<h4 id=‘date’></h4>
<img src="images/IMG_4945.jpg" alt="My test image">
</html>
My JS doc looks like this,
document.getElementById('date').innerHTML = new Date().toDateString();
My CSS doc looks like this,
body {
text-align: center;
background-color: #ffe6e6;
}
Hard to tell without looking at your file structure, but let's assume you have it like this:
|-Project
|-----css
|---------style.css
|-----js
|---------main.js
|-----index.html
in your index.html you should be calling your css like this:
<link rel="stylesheet" href="/css/style.css" />
in UNIX based OS's (and localhost Windows) / equates to document root. It's best to do this as you're guranteed to always call that file no matter where you copy + paste code to.
Note: In Windows servers / doesn't work - not sure why. Windows just sucks I guess.
Remove the async keyword from your script element. That isn't an asynchronous script and it modifies the DOM before it's ready.
Use jQuery $(document).ready(function() {}); or JS window.onload = function() {}; and remove that async attribute so your script is run in synch with the DOM.
In other words, you cannot edit the document before it has been created. But you are trying to do that with an async and no check for if the document is ready.
../ means parent folder. So:
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<script src="scripts/index.js"></script>
Double quotation marks in your code are valid? “ -> " Pls check it.
I can create a jQuery function within my HTML no problem:
<body>
<input type="text" id="mainInput" />
<button class="btn" id="mainButton"></button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#mainButton").click(function () {
$("#mainInput").hide("slow");
});
});
</script>
</body>
This does exactly what I intend it to do.
I read it was a good idea to create a separate script to contain the actual function, so I put the script in its own file...
<body>
<input type="text" id="mainInput" />
<button class="btn" id="mainButton"></button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="~/js/jQueryPractice.js"></script>
</body>
Here is the .js file with the jQuery
$(document).ready(function () {
$("#mainButton").click(function () {
$("#mainInput").hide("slow");
});
});
As soon as I do this, the functionality no longer works.
From everything I have researched, this should be working as intended; I have read multiple tutorials that use this method. I must be missing something simple...
This path:
src="~/js/jQueryPractice.js"
Uses ~, which doesn't really mean anything to a browser. What URL do you expect that to refer to? Should it be the root of the server?:
src="/js/jQueryPractice.js"
Relative to the page?:
src="./js/jQueryPractice.js"
Something else?
Whatever the URL is for the script, relative or absolute, that's what needs to be used in the src attribute.
Here is what got it to work.
My project has a 'wwwroot' directory. It was included when generating a new ASP.NET Core application through Visual Studio.
There is a js folder inside of this. When I put my script in there, the browser started finding it successfully.
This was the HTML:
<script src="~/js/jQueryPractice.js"></script>
The '~' seems to refer to 'wwwroot'. The script is now referencing and behaving as intended.
I know this stuff has been asked before...but I am a bit confused about this still. I have my index.html file and I have a script tag linking to my external JS file. If I only have that script tag the JS does nothing, but if I copy the JS and paste it into it's own script tag in the HTML header it works just fine. There's gotta be something I'm missing with Jquery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.2.0.js"></script>
<link rel="stylesheet" href="FinalProjectCss.css">
<title>Dustin Naylor - Final Project</title>
<script src="FinalProjectJS.js"></script>
<script>
$(document).ready(function(){
$(".section").click(function(){
if($(this).next().is(":hidden")) {
$(this).next().slideDown("fast");
} else{
$(this).next().hide();
}
});
});
</script>
</head>
<body>
<span class="section">Click Me</span>
<div class = "hiddenDiv">
Oh hey there.
</div>
</body>
</html>
So the code in the last script tag that is Jquery stuff is exactly copied into a separate JS file named FinalProjectJS.js. In the current state this code is in it works as desired, but when I remove that chunk of code from the html file it doesn't work....Sorry for my nubishness, I'm rather new and any help would be great! thanks!
Can you write the contents of your jquery file: FinalProjectJS.js? The syntax for calling the external file seems to be correct. So I'm thinking it might be something about the path or the jquery external file contents itself. Make sure you don't include <script> tags on that file. Here's a sample.
Another thing, last time I've worked with jquery, I can't directly see it take effect when both my files are stored locally. It had to be stored in a server first, then accessed by my PC. Only then did my jquery took effect. A dev I worked with added some text to my Google Chrome's properties (target) so that even if my file is not stored in a server, I can see jquery take effect even if both my HTML and jquery files are stored locally.
...sorry, I'm not allowed to comment yet to clarify your post.
You must add the jQuery script tag before FinalProjectJS.js for the jQuery snippet to work.
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous">
Can anyone tell me why none of the javascript/jQuery commands I try ever work on my computer, but always work on the internet? Here is an example of basic commands:
Javascript file (test.js), css file (test.css) (don't mind the css) and html file (test.html):
var $list = $('li');
$list.click(function() {
alert("working");
});
li {
list-style-type: none;
position: relative;
margin: 1px;
padding: 0.5em 0.5em 0.5em 2em;
background: grey;
}
li.done {
background: #CCFF99;
}
li.done::before {
content: '';
position: absolute;
border-color: #009933;
border-style: solid;
border-width: 0 0.3em 0.25em 0;
height: 1em;
top: 1.3em;
left: 0.6em;
margin-top: -1em;
transform: rotate(45deg);
width: 0.5em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<ul>
<li>Acheter du lait</li>
<li>Promener le chien</li>
<li>Faire de l'exercice</li>
<li>Coder</li>
<li>Jouer de la musique</li>
<li>Relax</li>
</ul>
</body>
</html>
See? It works on stack overflow. Yet, when I run the html file from my computer, the js/jq scripts never work. I know I haven't linked the js file improperly, because Safari developer tools are able to access it from the html file. What's wrong here?
If $list.click part is in test.js, then you are executing this code before li elements are constructed. Wrap your code in $(document).ready(function(){...})
Note:
It works here, because in the snippet frame source stackoverflow appended your javascript fragment below html - so that the code is executed when the DOM is fully constructed.
Try to write you code in $(document).ready() so that you DOM is ready to use, otherwise it may not work.
You have to add:
$(function(){
//Your Js code
});
In your example use:
$(function(){
var $list = $('li');
$list.click(function() {
alert("working");
});
});
Same problem:
Script tag works inside the body but doesn't work outside
Ok, I found it. I just had to wrap the code in
$(function(){
});
or
$(document).ready(function(){
//code
});
Thanks to Igor and JoanR.
The problems you are having may be related to how you are opening your web pages in the browser.
You cannot just open them as files: c:\website\index.html
Instead, you should install a stack such as WAMP, or XAMPP, or EasyPHP. I recommend XAMPP
After installation, you just type in the browser address bar:
localhost
And you will see the rendered contents of index.html from the c:\xampp\htdocs folder. That folder (c:\xampp\htdocs) becomes your website, and it works exactly like a website. Resources will load correctly (this sounds like the problem you are having).
After installation, just clear out that folder, and copy all your web site .html and .php etc files into that folder. Use the same folder structure you have on your website. A CPANEL website's public_html folder is the c:\xampp\htdocs folder on your C: drive.
If you create a folder in there, such as dev, and put a file inside it called mytest.html, then in the browser address bar you can type:
localhost/dev/mytest.html
Another great trick is to give yourself a domain by editing the Windows hosts file. For example, you can use the duchesne.com domain locally by editing this file:
c:\windows\system32\drivers\etc\hosts
Note that the file does not have an extension.
Then, inside that file, at the very very bottom, on a line of its own, type:
127.0.0.1 duchesne.com
After saving that file, when you type in the browser address bar:
http://duchesne.com
You will get the index.html file from your c:\xampp\htdocs folder. And if you type:
http://duchesne.com/dev
You will get the index.html file from your c:\xampp\htdocs\dev folder.
It is very important to NOT FORGET about that file! It will forever prevent you from accessing the online http://duchesne.com website. Of course, disabling it is as simple as commenting out that line (by putting a # in front) or by messing up the redirect, which is what I usually do:
127.0.0.1 xduchesne.com
(Deleting the leading x is easier than retyping the entire line). Coolest thing: the changes take place instantly, without rebooting -- or even bouncing the browser.
Resources:
Windows: XAMPP vs WampServer vs EasyPHP vs alternative
You might have to include the JQuery library for your website to know it is going to use JQuery. Here is one way to include it:
In the head tag of your html , paste the script below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
If You put Your html file via "drag&drop" to browser window, and You see file:// as protocol, then jQuery cant be downloaded from URL.
This is propably Your problem.
Edit:
I see Your JS code is inside test.js file which is loaded in head section.
So if this is still not working, try to replace code in Your test.js file to following:
$(document).on('click', 'li', function (){
alert('working');
});
It's times like these where CDN fallbacks are critical. Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
if (!window.jQuery) {
document.write('<script src="//code.jquery.com/jquery-1.10.2.min.js"><\/script>');
}
</script>
<script>
if (!window.jQuery) {
document.write('<script src="/Scripts/jquery-1.10.2.min.js"><\/script>');
}
</script>
If the Google CDN fails it loads jQuery CDN. If THAT fails too then it loads the local copy.
Just try if this can help
How about using a safe jquery coding ? like the codes below ?
jQuery(document).ready(function ($) {
$('li').click(function() {
alert("working");
});
});
or
jQuery(document).ready(function () {
jQuery('li').click(function() {
alert("working");
});
});
I have this short Javascript code that I want to put in a external file. The reason being is because there will be many .htm pages that would use it. So instead of putting it all inline at every single file, I want to put it in an external file.
But the thing is, it doesn't work. The script is basically a "back to top" button. It works flawlessly when I put the script in the .htm file. Another note by the way, I'm loading the .htm file in a Div, could that cause problems? Edit: The file is loaded through the .load() jQuery function.
I have also tried putting the script inline in my index.html but it fails to work there too.
Here is the code:
$('.backtotopwrapper').click(function(){
$('body,html').animate({scrollTop: "0px"},1500);
});
Update: I have tested my other .js code and the ones that have nothing to do with the .htm file work. The code that is specific to the elements inside the .htm is the only one that doesn't work.
OK, 3 files :
main.html
loremIpsum2.html
myScroll.js
1). In main.html I call jQuery and myScroll.js external files
Also I have an empty wrapper div (<div id="loader"></div>) where I put the contents of loremIpsum2.html using jQuery .load() so
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>link to external js file</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="myScroll.js"></script>
<script>
/* <![CDATA[ */
$(document).ready(function() {
$("#loader").load("loremIpsum2.html");
}); // ready
/* ]]> */
</script>
</head>
<body>
<div id="wrap">
<div id="loader"></div>
</div><!--wrap-->
</body>
</html>
2). In loremIpsum2.html, I have just a bunch of paragraphs but at the end I have my button :
<a class="backtotopwrapper" href="javascript:;">go to top</a>
3). In myScroll.js i Have the function for my scrolling button :
$(function () {
$('body').on("click", ".backtotopwrapper", function () {
$('body,html').animate({
scrollTop: 0
}, 1500);
});
});
Since I am loading the file where the button is via .load(), I am using .on() in its delegated form.
See DEMO and feel free to explore the source code.
NOTE : .on() requires jQuery v1.7+
I had the same problem but didn't perform any solution mentioned here, i actually dicovered what made it work for me when my external scripts werent working but the same code works internally.
Just remove any spaces/special characters from your external script filename e.g instead of calling it "admin-script.js", call it "adminscript.js", without the special characters like the hyphen, then refer to the script with the new name and thats it, it worked for me.