linking JavaScript to HTML file - javascript

I am at my wits end with linking a javaScript file to my main.html, they are both in the same folder.
I have viewed multiple Stack overflow topics regarding this question, and for some reason none of the solutions solve my answer.
My current code is what I have below:
[main.html]
<!DOCTYPE html>
<head>
<link rel="javascript" href="jsfile.js">
<title>JavaScript</title>
</head>
<body>
<div class="Header">
<h1>JS Basics</h1>
</div>
</body>
[jsfile.js]
document.write("Hello World");
This code does not display the "Hello World" message, however if i insert the code directly into the HTML file it does.
I appreciate any and all help on this matter.

Add like following not with link.
<script type="text/javascript" src="jsfile.js"></script>

Just type:
<script src="yourJavascriptFilename.js"></script>
Most importantly add this line to the bottom of your body tag to avoid your browsing requesting JavaScript to be loaded before displaying your HTML.

You're using the incorrect link for JavaScript.
Try using this instead
<script src="jsfile.js"></script>

Related

Wordpress: how to use javascript variables into html body

I'm really new in Wordpress, Javascript and HTML so I know this question is really basic, but I wasn't able to find it solved anywhere.
I want to create some variables in javascript and then display them in my page which is created in Wordpress.
Reading other posts I've found I need to insert a javascript code that at the end stores my variable this way (dummy version):
<script type="javascript">
document.getElementById('test').innerHTML = 'hello';
</script>
And then on the text block I want to display my variable to be displayed I should add this code:
<body>
<p id="test"></p>
</body>
However I've tried adding the javascript in the header (Tatsu header) and also tried adding it in the text block (HTML version) in different combinations and it never worked. Tried adding the script block before and after the body block, and also tried having it inside, before and after the display line.
If I try the following it works:
<body>
<p>hello</p>
</body>
So I guess my problem is that I'm not setting the variable properly.
Can anyone help? Apologies if this is already solved somewhere, spent some hours and wasn't able to find it.
Thank you in advance.
Your problem is the type of which you're using here:
<script type="javascript">
I noticed this whilst constructing an example of this problem.
javascript is not a correct mime type.
It should be text/javascript as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Please note this is not a complete list. Such as application/javascript also being valid. Please also see https://www.iana.org/assignments/media-types/media-types.xhtml
Working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="test">
This shouldn't show up
</p>
<script type="text/javascript">
console.log("####### JAVASCRIPT IS RUNNING ######")
document.getElementById('test').innerHTML = 'hello';
</script>
</body>
</html>

Using jquery in js file

Okay so all I am trying to do is make the jquery work in my javascript file which is linked to a html file. I created a totally new file for this to test it. The whole contents of the html file are:
<!DOCTYPE html>
<html>
<script src="C:\Users\Me\Desktop\Programming\jquery-1.12.4" type="text/javascript"></script>
<script src="check.js"></script>
<head> <h1>test</h1>
</head>
<body>
</body>
</html>
And the whole content of the js file is
$("h1").css("color", "red");
But when I open the html file in chrome the change I put in the js file with jquery doesn't show up (e.g the heading is not red). I just want to figure out how to make it so that it does.
EDIT:
Thanks for the help everybody, I was able to make it work :)
did you try this?
$(document).ready(function(){
$("h1").css("color", "red");
});
not sure but, does your browser access local files directly? im pretty sure that browser sandbox gonna reject that, maybe cors plugin on chrome?
EDIT:
try importing this instead...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Move your <h1> tag to be in the <body>
Move your <script> tags to the <head>
Replace your code in your JS file with what imvain2 said, so
that the JS will load once your document is ready.
Make sure you are correctly referencing your jQuery script. You can even use this to test it out:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Try to use jQuery CDN, this way you don't need to worry if jQuery loaded correctly or not.
$(document).ready(function() {
$("h1").css("color", "red");
});
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="check.js"></script>
<head></head>
<body>
<h1>test</h1>
</body>
</html>
There are a couple issue as described in other posts. All your meta, script, css references, etc. should go int the <head> and never header tags. Also need to correctly reference your javascript files.
<head>
</head>
<body>
<header>
<h1>test</h1>
</header>
</body>
Example: JSFiddle
If you want to use jquery in .js file all you need to do is type: src=" ..." above code.

Implement JS in HTML

It should be easy,
but as easy as it should be I can't solve the problem.
If I'm typing the following HTML and JS code into an online editor,
everything works fine but if I'm typing this into my (offline) editor it won't work.
Here's the online code:
http://jsbin.com/kenurunahu/1/edit?html,js,output)
I bet it has something to do with the loading order and how the files are linked.
Thats how my (lokal) HTML-file looks like (where the files are linked):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
<script src="Script.js"></script>
</head>
<body>
<p id="demo">
something
</p>
</body>
</html>
Many Thanks for Help!
[Update]
Firefox and Chrome display the JS file. Sometimes I get an error message that says 'innerHTML is null', but if I write the same code into the console everything works fine.
you have the error when the js script is loaded before the html dom is fully loaded by the browser. A simple solution for your testing is to place the script include at the end of your html page, like this :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
</head>
<body>
<p id="demo">
something
</p>
<script src="Script.js"></script>
</body>
</html>
A better solution is to run your script only when the dom is fully loaded. For example with the body onload event :
<body onload="yourFunc()">
Or event better by using only js code, for example with jquery ready function or by writing a simple custom handler that should work on all major browsers :
document.addEventListener("DOMContentLoaded", function(event) {
//call your func here
});
Hope that helps.
A few guesses:
Capitalization is important. If the file is named script.js do not link to Script.js
Is your js file in the same folder as the index.html document? Because that is what you are saying.
Normally, we arrange our file structure something like this:
public_html
- css
- js
- img
- inc
If your styles/scripts are stored in sub-folders, such as js and css, then you must amend your references to:
<link rel="stylesheet" content="css/Index.css">
<script src="js/Script.js"></script>
As a good practice, your scripts should be placed at the closing of body tag. External scripts are blocking and hence it would make sense we do not put them at the top. Also, when your script placed at the top runs, your DOM may not be ready, which means any element your script is trying to access may not be present in DOM at all which results in your error.
Hence, all your scripts should be at the closing of body tag. That way when the script loads and runs, you can be assured that the DOM is ready.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
</head>
<body>
<p id="demo">
something
</p>
<script src="Script.js"></script>
</body>
</html>

Javascript Runtime error: $ is undefined

I have added script in my Default.aspx page. I am getting following error.
$ is defined by jQuery, which you probably haven't referenced. A simple way to get it is to add one of the CDN urls to your template HTML:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
You need to include jQuery: http://learn.jquery.com/about-jquery/how-jquery-works/
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
**<script src="jquery.js"></script>**
</head>
<body>
...
</body>
</html>
I had the same problem, but did have a correct reference to jQuery.
I solved it by referencing jQuery before any other scripts. In your case, it would look like this:
<script src= "scripts/jquery-ui.js" />
<script src= "scripts/JavaScript_scroll.js" />
Hope this helps anyone else with a similar issue.
I had the Same Problem as that $ is Unidentified, After a long struggle, I come to know that there is some thing HTML coder error in Master Page, So it worked fine when i include the Jquery files directly in Content page
(For others who may face the same problem as OP's)
I had the same problem, but the reason was that I was trying to load my jQuery script before loading the jQuery library itself. In other words, make sure that you first add this line:
<script src="Scripts/jquery-{version}.min.js"></script>
before adding
<script src="Scripts/JavaSript_scroll.js"></script>

Can't import javascript code with innerHTML

I've built a webpage that is basically a main-page with a div that is filled with different pages by using AJAX. This basically works by loading pages into a div by using innerHTML. One problem I ran into was when a page with javascript is loaded into that div all of the other code runs fine; just the javascript doesnt work.
Main-page(index.php):
<html>
<head>
<script type="text/java">
////bunch of functions////
////Ends up that page_request on this instance is 'graph.php'////
document.getElementById('mydiv').innerHTML=page_request.responseText
</script>
</head>
<body>
<div id="mydiv"><div>
</body>
</html>
Child-page(loaded in div(graph.php)):
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" media="screen" />
<script src="other_stuff.js"></script>
</head>
<body>
<script>
///bunch of script////
</script>
</body>
</html>
Now when loading the page itself (opening graph.php) I notice that everything works fine; it is just when I import graph.php to index.php through innerHTML into my div it does not work (no errors just nothing is shown). I have read through many other posts and guides and did not come up with any distictive solution; thinks I have seen were:
Put eval() around my code [I saw on a guide that this could lead
to malicious user attacks].
Create the scripts on the main page then just import the data using:
document.createElement() and .parentNode.insertBefore()
Create a listener and call the functions when I open graph.php
And this good example
Even though I am not 100% sure how this example could work because I have php populate information for the javascript to collect and then make my graph on graph.php; so if I put that function into index.php the php will already be loaded so I would have to refresh the page or call them to update information somehow. Just for some context I am ok at php but I am new and struggle with javascript so I do not know what solution would fit my situation or work the best. Any tips/examples would be greatly appreciated, thank you for your time.
From you code snippets it seems you're looking to embed complete pages within the main page. If that's the case, a more straightforward approach would be to use an iframe element instead.
For example:
...
<div id="main-page-container">
<iframe src="some-path/graph.php" scrolling="no" frameborder="no"></iframe>
</div>
...
See reference and usage example.
I would suggest using jQuery's .load() function for this.
Take a look here: jQuery API
Older browsers such as IE8 and below don't allow you insert a string that contains javascript and execute it, in any form.
Take for instance:
function addScriptText(js_code) {
var element = document.createElement("script");
element.innerHTML = js_code;
document.head.appendChild(element);
}
will not work in IE8 and below.
You must use eval to accomplish this:
function addScriptText(js_code) {
window.eval.call(window, js_code);
}
Otherwise you need to dynamically request an external js file such as:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "externalScript.js";
document.getElementsByTagName("head")[0].appendChild(script);
Note: The page you are loading (page2.html in this example) must be on the same domain as the page that is loading it (page1.html in this example)
Working solution with jQuery:
Page 1:
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#page2").load("page2.html");
});
</script>
</head>
<body>
<h1>Page 1 Header</h1>
<div id="page2">
</div>
</body>
</html>
Page 2:
<h2>Page 2 Header</h2>
<script type="text/javascript">
alert("Page 2 loaded and javascript executed!");
</script>

Categories