JS and CSS not loading in html - javascript

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.

Related

javascript error - Scripts are not found

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var path = '/Scripts/';
document.write('<base href="' + path + '"/>');
</script>
</head>
<body>
<h1>WELCOME</h1>
<script src="test.js"></script>
</body>
</html>
test.js
console.log("Message from external script");
output
error.png
Here you can see, first it try to load the script from body tag before it get the actual base href path from script section.
Is there any way to get come out from this error? I mean not to load body script until base href set.
Once the base href set, it executed successfully.
Thanks.
The behavior you're seeing is (somewhat) browser-specific, and is related to your use of document.write to set the base href dynamically.
Chrome and Firefox try to load the page resources before applying the document.write, then updates those urls and tries again after you set the page <base>. Safari appears to not do this; it uses the inserted base href immediately. I have not tested other browsers.
(In all browsers the <base> tag, whether static or dynamic, needs to appear in the document before any links that depend on it.)
Other than the extra network request this seems to be harmless (see below), but you could avoid it by using a static <base> tag instead of dynamically writing one in, or by setting the full path on the <script> tag instead of depending on the <base>.
(re "harmless": I checked the case where a test.js exists both at the root level and inside the "/Scripts" directory. Dynamically inserting the "/Scripts/" base href did not cause both scripts to execute in Chrome: successful network requests for both test.js files were made, but only the code in "/Scripts/" was executed. So the browser makers have handled that edge case already. Good job, browser makers!)
You Can use this code
<script src="./scripts/test.js" type="text/javascript"></script>

Javascript(Jquery) executes in HTML header but not not when in an external JS file

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">

HTML is not reading external Javascript file

I am trying to write a very simple HTML page that displays a message generated by a JS file. I am somewhat new to HTML / JS and I am certain there is something pretty simple I am missing, but I cannot for the life of me get the page to read the script. When I load the page, it is completely BLANK without any errors in the inspector.
This is the project folder structure:
-Project (folder)
--templates (folder)
----home.html
--src (folder)
----home.js
--styles (folder)
----home.css
Also, I'm pretty sure that my HTML page SEES the script, because when I remove or rename the script, I get an error in the browser's inspector telling me that it cannot find the script. So it SEES the script, it just is not running it for some reason.
Here is the code...
home.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="../styles/home.css"></link>
<script type="type/javascript" src="../src/home.js"></script>
</head>
<body>
<div id="bodytext"></div>
</body>
</html>
home.js:
(function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
})();
Could some generous soul out there please clue me in to what extremely simple mistake I'm making?
Thank You!
Value for type attribute should be text/javascript as follows:
<script type="text/javascript" src="../src/home.js"></script>
Your script is running before the DOM is completely done loading. If you put your <script> tag right before your closing body tag (</body>), it will run after the DOM is loaded, and you will be able to traverse the DOM like normal.
Value for type attribute should be text/javascript as follows
enter code here
ALong with this you will have to change your java script code as follows, so that script gets executed only when page is completely loaded & document object is availabe.
window.onload = function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
};
What worked for me was adding charset="utf-8" to my css link as well as my javascript script (for me, both did not work). Example:
<link rel="stylesheet" type="text/css" href="css/main.css" charset="utf-8"></link>
<script src="javascript/script.js" charset="utf-8"></script>

Embed markdown (md) into HTML

I need help embedding a markdown, or *.md, file inside of an HTML index file. I have found that I can embed HTML inside of markdown, but not vice-versa. This would help to increase the speed of my editing because markdown format is extremely easy to use, (as I'm using it now) and I don't have to change the format of the rest of my site. I know that something like this is done to embed another HTML file with <iframe src="path/to/html>html-name</iframe>. I could also use javascript to interpret the md format on page load. Thanks ahead of time.
Here's the solution that I have long since forgotten about:
Forgetting that I asked this question and getting no answers, I created my own solution as an extension off of Chris Jeffrey's marked.js.
I call it tagdown.js.
Here it is: http://spikespaz.com/tagdownjs/
Just in case that link, or my domain, expires: https://spikespaz.github.io/tagdownjs/
Github: https://github.com/spikespaz/tagdownjs
This allows markdown to be added directly to the site, within a tag set with the class markdown. See the example on the site. There is no theme system in it, it's just the markdown parser.
Update
The project, TagdownJS, has been deleted from Github. The code for it seems so simple that it doesn't deserve its own repository.
Until it finds a new home, just go find Christopher Jeffery's Marked.js, and use this following code with it.
document.body.style.display = "none"; // Hide the page until it's finished rendering.
document.createElement("markdown");
var md_tags = document.getElementsByTagName("markdown"); // Returns array of all markdown tags.
for (var i = 0; i < md_tags.length; i++) { // Iterate through all the tags, and generate the HTML.
var md_text = md_tags[i].textContent.replace(/^[^\S\n]+/mg, ""); // I love regex, so shoot me.
var md_div = document.createElement("div"); // Make a new div to replace the fake tag.
md_div.id = "content";
md_div.innerHTML = marked(md_text);
md_tags[i].parentNode.appendChild(md_div); // Add remove the old raw markdown.
md_tags[i].parentNode.removeChild(md_tags[i]);
}
document.body.style.display = ""; // Show the rendered page.
https://github.com/zhlicen/md.htm An example of zeromd.js Just serve the md.htm file and md files, and visit directly by url:
/md.htm?src=README.md
Live demo: https://b.0-0.plus/blog/md.htm?src=https://raw.githubusercontent.com/microsoft/vscode/main/README.md
Basicly, you need to interpret MD format into HTML. Javascript is an option.
Take below as an example. (Though Windows, independent of OS)
Let's say a folder mytest looks like,
D:\mytest>dir
Volume in drive D is Data
Volume Serial Number is ABCD-EFGH
Directory of D:\mytest
12/03/2020 10:10 AM <DIR> .
12/03/2020 10:10 AM <DIR> ..
12/03/2020 10:09 AM 7,973 example-image.jpg
12/03/2020 10:12 AM 4,619 md_html.html
12/03/2020 10:00 AM 2,299 md_html.min.js
3 File(s) 14,891 bytes
2 Dir(s) 778,204,147,712 bytes free
D:\mytest>
Here is the html content,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/atom-one-light.min.css" />
<link rel="stylesheet" href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" />
<title>Marked In HTML</title>
</head>
<body>
<template type="markdown">
Try Marked In HTML !
====
</template>
</body>
<script src="https://cdn.bootcss.com/marked/0.3.6/marked.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/languages/javascript.min.js" charset="utf-8"></script>
<script src="md_html.min.js" charset="utf-8"></script>
<script type="text/javascript">
markedInHtml.init()
</script>
</html>
And the js,
!function(n){function t(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return n[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var e={};t.m=n,t.c=e,t.i=function(n){return n},t.d=function(n,e,r){t.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:r})},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=1)}([function(n,t,e){"use strict";function r(n){return n&&n.__esModule?n:{default:n}}function i(n){if(Array.isArray(n)){for(var t=0,e=Array(n.length);t<n.length;t++)e[t]=n[t];return e}return Array.from(n)}function a(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.MarkedInHtml=void 0;var o=function(){function n(n,t){for(var e=0;e<t.length;e++){var r=t[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),u=e(3),l=r(u),s=e(2),c=r(s);t.MarkedInHtml=function(){function n(){a(this,n),l.default.setOptions(this.options||{gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,smartLists:!0,smartypants:!1,highlight:function(n,t,e){return c.default.highlightAuto(n).value}})}return o(n,[{key:"init",value:function(){var n=this;document.querySelectorAll('template[type="markdown"]').forEach(function(t){var e=document.createElement("div");e.innerHTML=n.parse(t),e.id=t.id,e.classList.add(["markdown-body"].concat(i(Array.from(t.classList)))),e.dataset.markdown=n.intelligentProcessingIndent(t),t.parentElement.replaceChild(e,t)})}},{key:"parse",value:function(n){return(0,l.default)(this.intelligentProcessingIndent(n))}},{key:"intelligentProcessingIndent",value:function(n){var t=n.innerHTML.split("\n");t.length&&/^\s*$/.test(t[0])&&t.shift(),t.length&&/^\s*$/.test(t[t.length-1])&&t.pop();var e=Math.min.apply(Math,i(t.map(function(n){return n.length?n.match(/^\s*/)[0].length:1/0})));return t.map(function(n){return n.substring(e)}).join("\n")}}]),n}()},function(n,t,e){"use strict";var r=e(0);window&&(window.markedInHtml=new r.MarkedInHtml)},function(n,t){n.exports=hljs},function(n,t){n.exports=marked}]);
And the jpg,
After open the html, you should be able to convert
Try Marked In HTML !
====
into
You can try to replace the template, some effect may not be able to present. For example, use quick markdown example by John Gabriele, the equation are not shown well.
Someone, like 🎅 would suggest to use snippet, yet I failed to get that ❄️ work, parsing not successful. 🥺

Different alternatives for making the Jquery Library work

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

Categories

Resources