External Javascript doesn't load in VSCode - javascript

I'm working in VSCODE. I have an html page and I want to include an external javascript file in it.
this is the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()">
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
</body>
</html>
I know for sure that the js I wrote works, because if I put the js directly inside the <script></script> the page works.
Any idea on why, if I put it into an external file, it doesn't load? I'm also sure that the path "./index.js" it's correct.
I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
when I execute npm start it compile and gives me an http://localhost:xxxx

To make an example...
Maybe the script have an error?
function addTable(table) {
//Maybe you miss something? Here's an example
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 2; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()"></body>
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
<!-- add this -->
</body>
</html>
You can find more explanations of this JScode in this great page
Divertiti

I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
It sounds like you are using the Live HTML Previewer extension which says:
Note: Javascript is not supported in preview
Use a browser to test your browser-dependant JS.

Related

How do I make my copy to clipboard buttons work in a fetched JSON table?

first post and code newbie here. Be kind :-)
So I've got this fetched and into JSON converted data from an example API where certain colors with their HEX codes are displayed. I tried to include buttons after every HEX code, so that whenever u like a color, you can easily copy the HEX via button click. However i can not make the functionality of the buttons work. Any tips, hints, whatsoever?
Appreciated!
fetch("https://api.sampleapis.com/csscolornames/colors")
.then(response => response.json())
.then(json => {
let li = `<tr><th>Name</th><th>Hex</th></tr>`;
let copyButton = `<button onclick="goCopy"><i class="fa-regular fa-copy"></i></button>`
json.forEach(color => {
li += `<tr>
<td>${color.name}</td>
<td class="test">${color.hex} ${copyButton}</td>
</tr>`;
});
function goCopy() {
// Get the text field
var copyText = document.getElementsByClassName("test");
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);
// Alert the copied text
alert("Copied the text: " + copyText.value);
}
document.addEventListener("click", () => {
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>c</title>
<link rel="shortcut icon" href="./IMG/favicon-96x96.ico" type="image/x-icon">
<!-- CSS Stylesheet -->
<link rel="stylesheet" href="./CSS/style.css">
</head>
<body>
<div class="container">
<h1 class="header">c</h1>
<!-- Suchleiste -->
<form action="" class="searchbar">
<input type="text" name="" id="searchInput" onkeyup="tableSearch()" placeholder=" Suchen" style="font-family:Arial, FontAwesome" />
</form>
<!-- Tabelle für Daten-->
<table id="colorTable"></table>
</div>
<script src="./index.js"></script>
</body>
I tried giving the second row of a class, but I am not really sure how to make each button work it's own HEX code.

getElementById does not call the HTML ID

I have a folder with two files each, once the HTML file, and once the JS file to make everything clearer. My problem now is that I try to access an ID within the HTML file with the getElementById but this doesn't seem to work.
var score = 0;
score = score + 1;
document.getElementById("score").outerHTML = score;
<!DOCTYPE html>
<head>
<title>Clicker Game</title>
<link rel="stylesheet" href="design.css">
<script src="code.js" type="text/javascript"></script>
</head>
<body>
<p>Cookies: <span id="score">0</span></p>
<img src="images/cookie.png" height="256px" width="256px">
</body>
</html>
I am trying to call the ID "score" in the HTML file to make sure that when I start the HTML file locally the number changes from 0 to 1.
Click on the number in the HTML file, which will change the value. You cannot change the value without a trigger in the HTML. Something needs to be clicked or changed for the value to appear.
Edit: And don't grab the outerHTML of the element. You are erasing the whole score span and replacing it with the count. Use textContent instead.
let elem = document.querySelector("#score");
elem.addEventListener("click", (e) => {
elem.textContent = Number(elem.textContent) + 1;
})
#score {
cursor: pointer;
}
<!DOCTYPE html>
<head>
<title>Clicker Game</title>
<link rel="stylesheet" href="design.css">
<script src="code.js" type="text/javascript" defer></script>
</head>
<body>
<p>Cookies: <span id="score">0</span></p>
<img src="images/cookie.png" height="256px" width="256px">
</body>
</html>

Position of script tag in html

I am trying to duplicate Expanding Text Areas Made Elegant
Basically it explains how we can achieve something like fb comment box, where its size increases as text files the textarea.
I have this in my index.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="test.js"></script>
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
</body>
</html>
And my test.js looks like:
This doesn't really works.
However if I move everything inside the js file to a script tag inside body then it works fine. So my index file would look like:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
<script>
function makeExpandingArea(container) {
var area = container.querySelector('textarea');
var span = container.querySelector('span');
if (area.addEventListener) {
area.addEventListener('input', function() {
span.textContent = area.value;
}, false);
span.textContent = area.value;
} else if (area.attachEvent) {
// IE8 compatibility
area.attachEvent('onpropertychange', function() {
span.innerText = area.value;
});
span.innerText = area.value;
}
// Enable extra CSS
container.className += ' active';
}var areas = document.querySelectorAll('.expandingArea');
var l = areas.length;while (l--) {
makeExpandingArea(areas[l]);
}
</script>
</body>
</html>
You're not actually using onload
Your formatting is so messed up it's hard to tell, but your init code is in a while loop at the bottom after your onload function.
When you include it in the <head> it runs before any elements exist. That's why the position of it matters.
In your browser(I recommend Chrome for testing) open up the developer tools(via right click and selecting inspect element) and make sure your test.js file's path is correct. Do this by selecting the 'Sources' tab on the top of the developer tools window and then selecting the test.js file on the list of sources.
I also consider it best practice to load your js files at the bottom of your web documents(before the last body tag) to guarantee they load AFTER your dom elements load.
try this in your code:
I have used inside a table andapply a css class "form-control". The properties of this text areas are in side tag in side
html code:
<html>
<body>
<table>
<tr>
<td>Description:</td>
<td><textarea name="DESCRIPTION" id="DESCRIPTION" class="form-control"></textarea></td>
<td></td>
</tr>
</table>
//css-code required inside html:
<style>
textarea.form-control {
height: auto;
resize: none;
width: 300px;
}
</style>
</body>
</html>

HTML & JavaScript Uncaught ReferenceError: addTable is not defined

I have a javascript file which contains some data array and a function. I am using this function to display a table on the html page when it loads and on the click of a button. The error I am getting is:
GET http://localhost:3000/views/table.js contracts.html:84
Uncaught ReferenceError: addTable is not defined contracts.html:84 onclick
My contracts.html file looks like this:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="/css/portalstyle.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body id="contracts">
<div id="wrapper">
<!-- Some Header code here -->
<div id="mytable"></div>
<div id="footer">
<table id="footer" style="width: 100%">
<tr>
<td valign="bottom">Company Name
<br />Tel Num
<br />Location, Postcode</td>
<td>
<button onclick="addTable(ORDER.orders)">Click me</button>
</td>
<td align="right" valign="bottom">
Home About Help Contact
</td>
</tr>
</table>
</div>
</div>
<hr />
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script src="../views/table.js"></script>
</body>
</html>
My javascript function file is called table.js and contains:
var ORDER = {
orders: []
};
function Order(ref, grower, item) {
this.order_reference = ("o" + ref);
this.grower_reference = grower;
this.item_ordered = item;
}
var order1 = new Order(1, "grower2", "item");
ORDER.orders.push(order1);
function addTable(orders) {
var table = document.createElement("TABLE");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
for (var i = 0; i < orders.length; i++) {
var order = orders[i];
var row = document.createElement("TR");
var refCell = document.createElement("TD");
var growerCell = document.createElement("TD");
var itemCell = document.createElement("TD");
row.appendChild(refCell);
row.appendChild(growerCell);
row.appendChild(itemCell);
var ref = document.createTextNode(order.order_reference);
var grower = document.createTextNode(order.grower_reference);
var item = document.createTextNode(order.item_ordered);
refCell.appendChild(ref);
growerCell.appendChild(grower);
itemCell.appendChild(item);
table.appendChild(row);
document.body.appendChild(document.createElement('hr'));
}
}
window.addEventListener('load', function() {
addTable(ORDER.orders)
});
Where do I need to define addTable? How should I do this?
Also, the error with the GET. This is the line where I include the script. How can I stop this error occurring?
Thank you for the suggestions. They helped me to look at the correct piece of code to find the error so I have no fixed it.
It was an error with my folders and the path I was specifying. I originally had my .js file in my 'views' folder and was using ../views/table.js. This threw the not defined error so I created a new folder called 'js' and copied the file into here and specified it using /js/table.js and now it works.
From what I understand ../ looked in the parent directory of the folder I was in, whereas I needed to be 2 folders up, so starting with just a slash started the search from the root directory, found a folder called js and then found the addTable function as expected.

Flickering when appending row to table JQUERY

I have read all the other articles and none seem to have helped.
The page in question is www.projectwhisper.net78.net
When the button is clicked, a row is added.
But if you look carefully, there is a flicker near the bottom of the table.
Here is the HTML of the page:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<p>Hi There!</p><button id="the_button">Click to add row</button>
<table id="content"><tbody></tbody>
</table>
<script type="text/javascript">
$("#the_button").click(function()
{
var row=$("<tr><td>This is a row</td></tr>");
row.hide()
row.prependTo('table > tbody');
row.slideDown(500);
});
</script>
</body>
</html>
DEMO
Try this
$("#the_button").click(function () {
var row = $("<tr><td>This is a row</td></tr>");
row.prependTo('table > tbody').hide();
row.show(500);
});
Each time the row is added to the top of the table tbody as a stack, since each element is prepended to the table tbody

Categories