My HTML file won't link with my Javascript file - javascript

I am trying to complete an exercise for one of my courses and my HTML file won't link with my Javascript file. I put the link between my HTML file and my Javascript file in the body of my HTML file but the files still won't connect. When I test this code in Microsoft Edge, the buttons simply do not work. Anybody know what the problem is?
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<button onclick = "startWorker()">Start Worker</button>
<button onclick = "stopWorker()">Stop Worker</button>
<ul id = "output">
</ul>
<script type = "text/javascript" src = "/js/script.js"></script>
</body>
</html>
Javascript
var worker;
function startWorker(){
worker = new Worker ("js/mod4_worker.js");
worker.onmessage = function(event){
document.getElementById("output").innerHTML += '<li>' + event.data + '</li>';
};
}
function stopWorker(){
worker.terminate();
}
Files

So, I would try my comments :
Change the script.js path to : "../js/script.js"
Change the worker passed script to "../js/mod4_worker.js"
As GGG said, using a path starting with "/", a slash, use the path from root. The full path is either :
Windows : file://DriveLetter:\REST_OF_PATH
Unix/Linux/OSX : file:///REST_OF_PATH
WebServer : http://domain/REST_OF_PATH
If the structure is from /webapp/ :
html/index.html
js/script.js
Accessing script.js from index.html needs to go back one folder (..) and then set the path seen here (js/script.js) which gives (../js/script.js) OR using full path (/webapp/js/script.js) which I wouldn't recommend because if you change "webapp" directory of location or URL (on WebServer)

Remove the / from your src in the index.html. So it should be
src = "js/script.js"
Why? When you begin the src value with a /, that means you're referring to an absolute path (in other words, it starts the path from your drive's root). My devtools shows it as
file:///C:/js/script.js
By removing the first / in your src, you're now doing relative pathing, and it will look in the correct place.

Permissions & File locations
(Stumbled on this Q and here's the only way I solved it...)
For me, I found it was a permissions and file location issue...
I'm running a local webserver on Ubuntu 18 Desktop, working with dev from a local folder linked to the web directory: /var/www/html/MY_DEV -> /home/me/MY_DEV. So, the www-data user couldn't actually "own" them like it needed to.
I use this setup just fine for PHP, HTML, and CSS just fine. But, if I include a javascript file via src="", no matter what I do, it doesn't work.
The only way I could get it to work on my desktop is if BOTH the served file (somefile.php or somefile.html) are physically at /var/www/html/...
And, of course accessing them at localhost/...
And, of course owning them obsessively with sudo chown -R www-data:www-data /var/www/html

Related

Downloading jquery library to project Error:java: Illegal char <:> at index 4: http:\api.jquery.com

I use Intellij Idea. I want to download jquery library to have access offline to it in Intellij Idea in my Spring Project. So I typed "Alt + enter" on the link
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
and chose "Download library".
The library has dowloaded, and the problem is that after it I can't run my program, because all the time I see
Error:java: Illegal char <:> at index 4: http:\api.jquery.com
without any path. I have't even have something like written in my whole project.
When I had just global link to "https://code.jquery.com/jquery-1.12.4.min.js" and had internet access all worked properly.
I tried to download library in local file and put in header link to it actually after deleting library from intellij. But still don't working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<input type="number" id="myInput" name="myInput" onchange="countOfTryings(this)">
<a name="toChallenge" href="http://some_web_site.com?parameter1=4">This is link</a>
<a name="toChallenge" href="http://some_web_site_other.com?parameter1=4">This is link 2</a>
<script>
function countOfTryings(variable) {
$('a[name="toChallenge"]').each(function () {
var oldUrl = $(this).attr("href"); // Get current url
var str = oldUrl.substring(0, oldUrl.indexOf("parameter1"));
var newUrl = oldUrl.replace(oldUrl, str + "parameter1=" + variable.value); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
}
</script>
</body>
</html>
I want my program to change the urls of hyperlinks with name="toChallenge". To change the value of the request parameter "parameter1" to new value, what will be in input with id="myInput".
After submiting a report to Intellij Idea I got an answer, that JS libraries are added to the Java classpath which is a bug, and to fix thit problem I need to do next:
Project settings (ctrl+alt+shift+s by default) -> Modules -> in "Modules" select "Dependencies" -> find jquery dependency -> delete jquery dependency -> click "apply"
I had same problem but deleting dependency did not help. I had to go to global libraries and delete jquery library as well.
[ctrl+alt+shift+s] -> Modules -> Dependencies -> delete jquery dependency
maven -> reload all maven projects
As both Jan and Odeta point out in their answers, this can be fixed by deleting the dependency in the module and global library. However, I think I can refine this a little further. When I looked under the global library, I found there was both the released artifact and a link to the documentation. If you delete the documentation reference, it should fix the problem and the dependency can remain.

Node.js. Working with the real path of local files

I'm new in Node.js and I'm doing a local App with Node.js+HTML5+Javascript with which I would like to move files from one local folder to another local folder. The main functionality of this app is to get a local file "A", read its content, copy this content encrypted in another file "B", and then store "B" in other location and finally delete file "A" in the local system. The problem that I've found is on getting the real path of the first file, and I know that it is difficult to get it (as I've seen in several discussions) for security reasons, but I really need it in order to delete file "A". I realised that with my current code I only can get this real path in IE explorer. The main part of the code involved is the following, in which I'm only able to get the file name in both Firefox and Chrome:
index.ejs:
<!DOCTYPE html>
<html>
<head>
<script src="../scripts/get_file.js"></script>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method='get' action='/moveFile'>
<div id="page-wrapper">
<h1>File Browser</h1>
<div>
Select a file:
<input type="file" name="fileInput" id="fileInput">
<input type="submit" value="Upload File"/>
</div>
</div>
</form>
</body>
</html>
get_file.js:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
});
}
fs_controller.js:
exports.moveFile = function(req,res) {
console.log(req.query.fileInput);
};
I've tried with the following options:
I've seen that bodyparser is only used for express 3.0, and I have
express 4.13.1.
I've tried with Busboy, without results.
I've tried with filepath utility, but it returns the path
where is the main script of the application, so it's not useful for
this case.
Formidable only returns a tmp path.
I've tried with multiparty, and it also returns a tmp path.
The only solution that may be could work is to modify some properties
in Firefox, like
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
and in Chrome, with --allow-file-access-from-files. However, I think
that it's not a clean solution.
I dont know if there are better solutions with Node.js to make this type of app. The main features that I actually need is to work with local files and folders (all types of basic operations with them), and to have a little database for storing the users of the app, and I would like to implement it with a MVC design pattern.
Thanks for your effort!

javascript method not working

this code is not working as expected
<html>
<head><title>alert()</title>
<script type="text/javascript">
function greeting()
{
var name=prompt("what's your name?","your name");
if(name){
alert("hi, " + name + " welcome to this page");
document.getElementById("im").src="F:\wallpapers\a.jpg";
}
}
</script>
</head>
<body onload="alert('hi, this is the alert() function');">
<img id="im" src="F:\wallpapers\Ubuntu_wallpaper__1_by_leroi14.jpg" onclick="greeting();" /></body>
</html>
document.getElementById("im").src="F:\wallpapers\a.jpg" is not displaying the image when given absolute path.
But it works if image is in same folder as this file.
can anyone help?
For whatever reason you use backslashes in your path, which need to be escaped in string literals:
"F:\wallpapers\a.jpg" === "F:wallpapersa.jpg"
Use "F:\\wallpapers\\a.jpg" or "F:/wallpapers/a.jpg" instead.
If you plan on serving this page to others, you don't want to use an absolute path. Javascript runs on the browser, and does not have access to the server's filesystem for absolute paths.
See answers here
It's common to have an images folder within your website's project folder. Put images in this folder, then you can use src="/images/a.jpg"

Load all xml files in a directory without knowing names with javascript

Stack
I am trying to dynamically display a product page in html that will be easy to edit. My set up is a bunch of xml files, one for each product, that will go into the same directory as the html page they go with. Then when the page loads, it also reads in all of the xml files in the directory with it, which could be changing pretty regularly.
I would like to do this in javascript, but I don't know how to develop a list of files in my current directory. The only information I can find talks about finding files on the clients computer which I do not need. I need to list all the files on the server in the current directory. I already have the code working for loading files once I know the name, I just need a list of filenames to put in the function.
As always thanks a lot for the help.
RShom
OK, doing this opens pandora's box, but also a lot of cool capabilities as well, too numerous to count.. Even without PHP, it's still totally doable...
One way:
Turn on XHTML file listings in Apache. Go to your /etc/apache2/httpd.conf, make sure you've uncommented
LoadModule autoindex_module libexec/apache2/mod_autoindex.so
as well as turned off any IndexOptions you may have and replace them with these...
IndexOptions XHTML SuppressHTMLPreamble Type=text/xml
Restart apache, browse to your configured VirtualHost.. and you should have a nicely styled file listing, with source that resembles this...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Index of /dir/CRUD</title>
</head>
<body>
<h1>Index of /dir/CRUD</h1>
<ul><li> Parent Directory</li>
<li> CRUD.aspx</li>
<li> CRUD.aspx.cs</li>
<li> member.xml</li>
<li> web.config</li>
</ul>
<address>Apache/2.2.17 (Unix) PHP/5.3.4 Server at yourserver,net Port 80</address>
</body></html>
As you can see, this is a fairly simple, valid XML file with whatever directory you're trying to list. Now, with a list of files in XML at your disposal, you can get as creative as you want in terms of styling, parsing, and doing with it as you please... You could easily setup an automated gallery that will show every file in the folder, or you could generate a javascript array with the info and perform a myriad other RSS, JSON, or whathaveyou functions with it.
Another way, does't require any changes to your apache IndexOptions, but they DO need to be enabled...
Create two HTML files on your server...
test.htm
<html>
<head>
<script>
function reload_main() {
window.main.location.href = "main.htm";
}
</script>
</head>
<frameset rows="*,1" onLoad="reload_main()">
<frame src="blank.htm" name="main">
<frame src="css/" name="directory">
</frameset>
</html>
main.htm
<html>
<body>
<h1>Contents of directory</h1>
<script>
var links_length = parent.directory.window.document.links.length;
var link = "";
for (var i = 0; i < links_length ; i++) {
link = parent.directory.window.document.links[i].href;
document.write(
''+link+'<br>'
);
}
</script>
<p>Return
</body>
</html>
This will get you the same thing, basically, but embedded in an invisible iFrame. Still, you can extract the subsequent <li> baboon.png</li> items and manipulate your XML to do whatever you want.
Easiest way is to have a script on the server which send the file names as a JSON encoded string.
This php script outputs all xml files with the .xml extensions that is in the same directory as the script (just change opendir to use some other path)
<?php
$files = array();
if($handle = opendir(dirname(__FILE__))) {
while (false !== ($file = readdir($handle))) {
if(substr($file, -4) == ".xml")
$files[] = $file;
}
closedir($handle);
}
echo json_encode($files);
?>
You would then in javascript just get the json with ajax, here using jQuery:
$.getJSON("http://example.com/path/to/script.php" function(files) {
// Do something with the files
});
The only other way would be to rely on the server producing an index (such as apaches autoindex) but that would be a lot more work.

Relative Paths in Javascript in an external file

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Categories