Own JavaScript not running - javascript

I'm starting to learn HTML5+CSS+JS. It was all going fine on my Windows desktop, but when I try doing something on my Linux notebook, no javascript seems to work.
This is the mini tutorial I followed: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript
and this is my page with the result: http://www.lele.bbt.net.ar/prueba01/
(As you can see, the JS is not doing a thing).
// JavaScript demonstration
var changeBg = function(event) {
console.log("method called");
var me = event.target,
square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(function() {
clearDemo(me)
}, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 120px;
height: 120px;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
</body>
</html>
(Here it works, but for some reason, not when I do it on my computer).
I don't know if it can be a priviledge problem or something like that (js has read/write priviledges, not execute. But I guess that's how it should be)
Thanks!

I'm pretty sure it's because the script can't find the button.
You load your script before everything else is loaded, which is fine. But you can have problems like this. To avoid this kind of problems you load the JavaScript file after the HTML.
At the moment if you try to print the var "button" you will receive "null".
The Chrome console when you open the page gives you this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
That means that it is trying to read the property of the button, which is null.
Move the script tag to the very end, just before the closing </body> tag:
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
<script type="text/javascript" src="script.js"></script>
</body>

Related

Trying to change background color with variable

Trying to change color using a variable, console works but color not changing when I click on the square.
Color is the variable I want to use.
I have tried an actual string value and that does not work.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColour = colour;
console.log(colour);
}
</script>
</body>
</html>
its backgroundColor not Colour .. you have an extra u
You need to replace backgroundColour by backgroundColor without u :
document.getElementById("shapes").style.backgroundColour = colour;
______________________________________________________^
Must be :
document.getElementById("shapes").style.backgroundColor = colour;
NOTE 1: You need to trigger the function to see the effect and you must also give your target div shapes a width/height so you can see it.
NOTE 2: You must listen on DOMContentLoaded event to make sure all the elements are loaded to the DOM before calling your script.
Working sample:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
#shapes {
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var shapes = document.getElementById("shapes");
shapes.addEventListener('click', myFunction, false);
});
function myFunction() {
shapes.style.backgroundColor = "#" + (Math.random() * (1 << 24) | 0).toString(16).slice(-6);
}
</script>
</body>
</html>
Try this
const shapes = document.getElementById("shapes"); // You declare once, then you can reuse
function myFunction() {
var colour = '#'+((Math.random() *(1<<24)|0).toString(16).slice(-6));
shapes.style.backgroundColor = colour;
console.log(colour);
}
shapes.addEventListener('click', myFunction); // I guess you want to click somewhere
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">Shapes</div>
Below code gives the expected result. please take it.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<style>
#shapes {
width: 300px;
height: 300px;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes" onClick="myFunction();">
test
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColor = colour;
console.log(colour);
}
</script>
</body>
</html>

Why isn't importNode executing when everything is fine?

I want to use HTML import so I created two files.
File1:
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
File2:
<!DOCTYPE html>
<html>
<head>
<link rel='import' href='test.html' id='LINK'>
<script>
var LINK = document.getElementById('LINK');
var test = LINK.import;
var content = document.importNode(test.content, true);
document.body.appendChild(content);
</script>
</head>
<body>
</body>
</html>
I should see a yellow square when I execute File2 but instead I'm getting this error:
Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
at Import.html:8
When I log the "test" variable to the console, I am getting the document that contains File1 so it's fine there. I just don't get what the error is supposed to mean and why it's not working.
When you write:
var content = document.importNode(test.content, true);
...you suppose that test is a <template> element.
So in the document you import, you should have a <template> element.
test.html:
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<template><div></div></template>
</body>
</html>
In the main file, use querySelector() (or another selector function) to get the template:
var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...

how to get the cssText of external style?

I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.
from the error message, yeah It's cssRules is null, surely error!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
external css
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
Thank your guys!
I suspect your JavaScript is running before the stylesheet is loaded. Try this:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
Or if you happen to be using jQuery, this is more universal:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.

Loading JavaScript in a Chrome Extension

This is my first post on SO and my first time making a Chrome Extension. I've read alot of documentation, but I am still unsure how to get this to work. Below are my html and js files. I want to be able to type something in the source box and have the have the word print out in the results area in real time. I have tested this code on my local host so i know it works, but for some reason it is acting up as a chrome extension.
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="source"></textarea>
<div id="result">
</div>
</body>
</html>
Here's the js:
function main() {
document.getElementById('source').keydown(function() {
var source = document.getElementById('source').value;
var outputValue = source.replace(/command/gi, "⌘")
.replace(/tab/gi, "⇥")
.replace(/return/gi, "⏎")
.replace(/option/gi, "⌥")
.replace(/control/gi, "⌃")
.replace(/esc/gi, "⎋")
.replace(/left/gi, "←")
.replace(/down/gi, "↓")
.replace(/up/gi, "↑")
.replace(/right/gi, "→")
.replace(/shift/gi, "⇧")
.replace(/eject/gi, "⏏")
.replace(/caps\s\(lock\)/gi, "⇪")
.replace(/save/gi, "⌘ + S")
.replace(/print/gi, "⌘ + P")
.replace(/find/gi, "⌘ + F");
document.getElementById("result").innerHTML = outputValue;
}
}
1) What wOxxOm said in the comment: element.keydown(function() { ... }) does not exist. This definitely comes from some jQuery code - you could use that if you add it to your extension, or you could use addEventListener.
2) You declare a function main(), but nothing ever calls it. A good place to call it would be a DOMContentLoaded event listener on document:
document.addEventListener("DOMContentLoaded", main);
function main() {
/* ... */
}

JavaScript html editing error

I am fairly new to JS, just writing some scripts to learn. Could someone show me where I'm going wrong here? I think it may just be a syntax error somewhere or that I haven't used the correct features for this task.
Thanks :)
HTML:
<!DOCTYPE html>
<html>
<head>
<title>javascript • training</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id='textOff'>
Hi there this is some sample text for my JS
</div>
<input type='submit' value='show me some stuff!' onclick='show();'/>
<script>
function show() {
var text = document.getElementByID('textOff');
console.log(text); //debugging
text.id = 'mainText';
};
</script>
</body>
</html>
CSS:
body {
background-color: #17161F;
color: white;
}
#mainText {
width: 20%;
height: 30%;
font-family: Arial;
margin-left: 20%;
margin-top: 20%;
}
#textOff {
display: none;
}
JavaScript is case sensitive.
getElementById // correct
getElementByID // incorrect
Use the JavaScript console provided by your browser:
TypeError: Object #<HTMLDocument> has no method 'getElementByID'
Use the JavaScript Console to detect errors in your JavaScript.
This would have flagged that getElementByID is a null reference.
Browser Console itself tells that there is error :
Uncaught TypeError: Object #<HTMLDocument> has no method 'getElementByID'
Replace getElementByID with getElementById.
function show() {
var text = document.getElementById('textOff');
console.log(text); //debugging
text.id = 'mainText';
};
Here is the working demo : http://jsfiddle.net/fh6NG/

Categories

Resources