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");
});
});
Related
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">
I'm trying to run the Socket.io example program offline. The index.html page calls the Jquery library like so:
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
However, this obviously won't load without an internet connection. I have tried using a file in the same folder as the rest of the project:
<script src="jquery-1.11.1.js"></script>
But I get a 404 error in the developer menu when running that as well. I'm not sure if I'm putting the file in the wrong spot, or if I'm using the script tag incorrectly, Any help is appreciated.
EDIT:
Here is the full index.html file:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="jquery.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
Picture of Error Message
Picture of index.js
If your Html and JS file are both in the same folder it should work definitely. Otherwise you need to put an address relative to your current file. Say your JS file is in the parent folder of your HTML file then :
<script src="../jquery-1.11.1.js"></script>
Maybe this question can help you with local local resources references How to properly reference local resources in HTML?
Don't forget you can access the jquery file by typing in the exact (local) URL into your browser.
Test by loading the URL http://localhost:[port#]/jquery-1.11.1.js
Alter this URL with the correct directory path for your dev environment until your jquery successfully loads.
Paul try followings:
Verify jquery file name and path
if socket.io.js using jQuery change the order like
<script src="jquery.js"></script>
<script src="/socket.io/socket.io.js"></script>
call javascript code after page load i.e. $(function(){}) as below:
$(function(){
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
})
Thanks
If your file is in the same directory as your html the following should make it work :
<script src="jquery-1.10.2.js"></script>
If it's in a folder that is in the same directory as your HTML use:
<script src="FOLDERNAME/jquery-1.10.2.js"></script>
If it's a level above your HTML file use:
<script src="../jquery-1.10.2.js"></script>
If none of these work be sure to double check your file's name in case there's a space in beginning or the end of the file's name.
[EDIT]
Well, if there's no spelling error and the change of placement doesn't fix it, then probably one or both of the files are corrupted. By the way, your jQuery version is outdated. Download v2.1.1 or use this script tag:
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ok, I recommend changing your index.js to server.js, it makes more sense that is more like a server file for your app. It will serve a lot more things not just the index page. However, you can name it whatever you want. :)
Your problem is that node does not know your file system. You send the index back with __dirname +/index.html. __dirname tells node the current directory but on your index file, script src on your index.html file does not know where to start.
On your index.js file, tell node where to get all the static files, between line 3 and 5 app this.
app.use('/s', express.static(__dirname + '/static'));
the '/s' is the alias for this static directory that we're going to define. __dirname is your root dirctory and '/static' is the folder where i want all my static files to be since i don't want to expose my whole root.
For that exact line to work, you will need to add a folder name "static" on the directory where your index.js and index.html is right now.
on your index.html file, instead of
<script type="text/javascript" language="javascript" src="jquery.js">
change the src to "/s/jquery.js" since node.js now knows what alias s represents.
<script type="text/javascript" language="/s/javascript" src="jquery.js">
good luck
I had the same problem and I was looking for the solution around. I found your question but I didn`t find the answer so I posted my own question here. Someone actually knew how to make it work. So if you still want to know just check the answer I got: Raspberry Pi - Flask Server using JQuery not working Offline (Online it works)
DIV tag is not rendering HTML file .
Whats the problem in coding mentioned below.Help
CSS:
#-ImageSlider
{
width:50%;
height:75%;
margin-left:3%;
margin-top:5%;
display:inline-block;
left: 100 px;
border:thick solid black;
}
JS:
<script type="text/JavaScript" language="JavaScript">
$(document).ready(function(e) {
$("#-ImageSlider").load("\Cover Slider\index.html");
});
</script>
P.S - CoverSlider is another folder which contains another project with html file index.html. It resides in working directory
check if you have spaces in it and \ these slashes, try replacing with this:
$(document).ready(function(e) {
$("#-ImageSlider").load("/CoverSlider/index.html");
}); //-----------------^-----^-----^--------------see this
As your comments:
Same folder d:/project/CoverSlider and all my files are in D:/project/
d:/project/CoverSlider this is not the way to do a ajax request. You have to setup a local server environment on your system. So if you do that then you can only access your page because .load() is an another ajax feature of ajax and ajax requests can only be done on server not in the file system.
try like this
$(document).ready(function(){
$.get('Folder/test.html')
.success(function(data) {
$("#-ImageSlider").html(data);
});
});
Like this
<script type="text/JavaScript" language="JavaScript">
$(document).ready(function(e) {
$('#ImageSlider').load("/Cover Slider/index.html");
});
</script>
demo1
please remove (-) in this "#-ImageSlider"
please write "#ImageSlider"
in id (-) is not required.
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.
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