I am making a very simple page that just counts how many seconds the user has had the tab open. In the console the seconds update, but on the page in the browser, it ain't.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
What is the problem?
The variable seconds is declared too soon before the element is even rendered, that's why I added the window.onload wrapper to your code.
You need to use innerHTML to change the content of a div element.
Not related, but you can also style the body tag via CSS rule.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.onload = function () {
var seconds = document.getElementById('counts');
var count = setInterval(counter, 1000);
function counter(){
var newCount = Number(seconds.innerHTML) + 1
console.log(newCount);
seconds.innerHTML = newCount;
}
}
</script>
<style>
body {
backgroundColor: "#EBE9BD";
}
h2 {
text-align: center;
color: #032441;
font-family: monospace;
}
div {
text-align: center;
color: #032441;
font-size: 70px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
You could use the following:
<script type="text/javascript">
window.seconds = document.getElementById('counts');
setInterval('counter()', 1000);
function counter(){
console.log(seconds.innerHTML);
window.seconds.innerHTML++;
}
</script>
Bare in mind that 'counts' is not yet defined as soon as the script runs.
To access the "body" of an Element you have to access it via element.innerHTML which in your case would look like window.seconds.innerHTML = window.seconds.innerHTML + 1
EDIT: But that won't fix your problem.
Your script does not detect the <div id="counts"> element, since it has not been loaded yet, you can fix this by moving the script after the div
Since innerHTML returns a string, performing + will attach both strings and your seconds will look like 011111111 So you'll have to parse it to a string via parseInt(window.seconds.innerHTML)
So changing
window.seconds = window.seconds + 1
to
window.seconds.innerHTML = parseInt(window.seconds.innerHTML) + 1;
and moving the script tag at the very bottom, should to the trick
Related
So I wanted to make a webpage in which on button click, the background color changes.
Its showing TypeError on loading in browser but its working fine after pasting same JavaScript on console.
Code snippet
var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];
var flag = 0,
blinkCount = 0;
function blink() {
if (blinkCount == 15) {
blinkCount = 0;
blink();
} else {
var h1 = document.querySelector("h1");
var body = document.querySelector("body");
h1.style.color = colors[blinkCount];
body.style.background = colors[blinkCount];
blinkCount++;
}
}
var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
width: 50%;
height: 100px;
background: black;
margin-top: 300px;
margin-left: 300px;
}
h1 {
color: #0af5fa;
}
body {
background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link href="../css/ex153.css" rel="stylesheet">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="">
<button><h1>Click Me</h1></button>
</div>
</body>
</html>
In Browser [Error]
TypeError: button is null[Learn More] ex153.js:25:1
You're running the script before the document has been fully parsed - see how the <script> is above the <body> and its <button>?
Either give the script tag the defer attribute:
<script defer src="..
Or move it to the bottom of the body:
</div>
<script src="../JavaScript/ex153.js"></script>
</body>
</html>
Or wrap the whole script in a DOMContentLoaded listener:
document.addEventListener('DOMContentLoaded', function() {
var colors;
// other code
});
I am trying to make another div right under the existing div in the HTML
<html>
<head>
<title>
Media Player
</title>
<script src="script.js"></script>
</head>
<script>
makeOscarPlayer(document.getElementById("my-video"))
</script>
<body>
<div class="my-player">
Hello!
</div>
</body>
</html>
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `
hello
`
}
can someone explain to me what I am doing wrong? I am a self-taught developer sorry if my code is not perfectly organized still learning
You are calling the makeOscarPlayer() function before you are creating it.
You need to wrap the makeOscarPlayer() function declaration in a script tag.
You are passing in document.getElementById("my-video") as a parameter to makeOscarPlayer(), but there is no HTML element with an id of 'my-video'. You are giving the function a parameter of null, while the function declaration has no parameters.
You need to tell the script where to put the new element. To do that, you grab an existing element and use parentNode and insertBefore
Here is a barebones version that I got working for your reference:
<html>
<head>
<title>
Media Player
</title>
</head>
<script>
</script>
<body>
<div id="my-player">
Hello!
</div>
</body>
</html>
<script type="text/javascript">
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `hello`;
// This grabs the element that you want to create a new element by
var existingDiv = document.getElementById("my-player");
// This tells the script where to put the new element
existingDiv.parentNode.insertBefore( div, existingDiv.nextSibling);
}
// Must be called in the same script block or after the script holding the function declaration is loaded
makeOscarPlayer();
</script>
For more information on how parentNode and insertBefore work, see this Stack Overflow question
You need to append that new element to a specific parent, in your case to my-video.
The function appendChild appends the new element to a parent element.
function makeOscarPlayer(parent) {
var div = document.createElement("div");
div.innerHTML = 'Hello from Ele';
parent.appendChild(div);
}
makeOscarPlayer(document.getElementById("my-video"))
#my-player {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 300px;
background-color: #f1f1f1
}
#my-video div {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 200px;
font-weight: 700;
}
<div id="my-player">
Hello!
<div id="my-video">
</div>
</div>
It's a good start, but you're calling the function incorrectly and your function isn't adding anything to the page.
we use appendChild to add a node to the page.
In your function you create and add text to a div, but you don't return the node you made(and also you didn't close your line of code with a semi-colon so I added that too) but this should work:
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<div class="my-player">
Hello!
</div>
<script>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
</script>
</body>
</html>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<!-- added my-video div -->
<div id="my-video"></div>
<div class="my-player">
Hello!
</div>
</body>
</html>
I have this code, and it is working fine on my test website but not in a browser as local (on my hdd) standalone page
Here it the code in jfiddle: https://jsfiddle.net/9jdsvjfb/
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
function toggleDiv(divId) {
var ele = document.getElementById(divId);
ele.toggle();
}
</script>
<style>
a:hover {
color: purple;
}
a:active {
color: purple;
}
</style>
<title></title>
</head>
<body>
<a class="ConceptLevel1" href="javascript:toggleDiv('PktS/h+L5EeSqM/4hMH9JA==');"
style="text-decoration: none; font-weight:bold; font-size:13pt">BGP -concept list</a>
<br />
<div style="padding-left:15px;" id="PktS/h+L5EeSqM/4hMH9JA==">
<div>fds</div>
<div>sdfdsfdfdsf</div>
<div>sdfsdf</div>
<div>gdhgf</div>
<a class="ConceptLevel2" href="javascript:toggleDiv('SPrQVTbDx0WO6As2F+43tw==');"
style="text-decoration: none; font-weight:bold; font-size:12pt">hfghg</a>
<br />
<div style="padding-left:15px;" id="SPrQVTbDx0WO6As2F+43tw==">
<div>hfghgh</div>
<div>fghfgh</div>
</div>
</div>
</body>
</html>
I can see two problems here. First, Divs doesn't have a toggle function; I think you mean:
function toggleDiv(divId) {
var ele = jQuery('#' + divId);
ele.toggle();
}
The other problem is in the jsFiddle: since jsFiddle sends all Javascript wrapped inside a function (in windows.load) it is needed to define the function toggleDiv as a global variable, for it to be found when clicking the link:
window.toggleDiv = function (divId) {
var ele = jQuery('#' + divId);
ele.toggle();
}
Just a final note: It may be better if instead of embedding the Javascript insite the HMTL, you use events in order to bind the toggle function to the links' click event.
This is my javascript for replacing some text:
document.body.innerHTML = document.body.innerHTML.replace(/Sometext/g, 'difference');
Ho do I change color, font-size, font and such?
I need to link my script like this, can't use { otherwise:
<script>$(document).ready($.getScript("url"));</script>
I though something like this would work:
window.onload = function() {
document.body.innerHTML =
document.body.innerHTML.replace(/Deckling/g, result);
}
var str = "The Liberator";
var result = str.fontcolor("Red").italics().fontsize(6);
result.style.fontFamily = "Harrington";
Any help? (first post and very limited Knowledge)
You can wrap you text in a div or span tag, select it in JS applying a class.
The class will contains the style for your text.
Just a quick example in vanilla javaScript (no jquery):
http://jsbin.com/yufiteseme/1/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.a {
color:red;
font-style: italic;
font-size: 6px;
{
</style>
<script>
function changeColor(){
document.getElementById('text').classList.add('a');
}
</script>
</head>
<body onload="changeColor()">
<div id="text">
Test for example
</div>
</body>
</html>
You can change style of an html element using javascript, put your script below the element.
The following example changes the style of a 'p' element using javascript:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").style.color = "red";
document.getElementById("p1").style.fontFamily = "Arial";
document.getElementById("p1").style.fontSize = "larger";
</script>
</body>
</html>
You can also change style of an html element using jquery.
The following example changes the style of a 'p' element using jquery:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#p1').ready(function(){
$('#p1').css({"color": "green"}).css({"fontFamily": "Arial"}).css({"fontSize": "24px"});
});
</script>
</head>
<body>
<p id="p1">Hello World!</p>
</body>
</html>
That will not work:
var result = str.fontcolor("Red").italics().fontsize(6);.
You need to add css to change the surface.Add this to your header:
.textstyle{
font-size:16px;
font-family:Harrington;
}
</style>
And add this to your window.onload:$('body').addClass('textstyle');
I am trying to set up localStorage to have when the button is clicked the number of times the background color has changed is stored there. I also need to be able to clear it at any given point in time, and finally When the document starts, or the page reloaded, access the count that was saved in the above step. If there is not any data – then this is the first time to the web site so there is no need to show the count.
I do not know where to put the localStorage to be able to grab the count, or how to set up the button to clear the localStorage, sorry folks I am very new at all of this and having a very hard time trying to learn this. I am not looking for anyone to write code for me I am just looking for suggestions on what to do next
The code is below any help is greatly appreciated
Thanks all!
<!DOCTYPE html>
<html lang="en">
<head>
<title> </title>
<meta charset="utf-8">
<script type="text/javascript">
var count = 0;
var interval;
function getRandom(num){
return Math.floor(Math.random()*num);
}
function changeColor(){
count ++;
var num1 = getRandom(255);
var num2 = getRandom(255);
var num3 = getRandom(255);
var col = "rgb("+num1+","+num2+","+num3+")";
var div = document.getElementById( 'myDiv' );
div.style.background = col;
}
function stop() {
clearInterval(interval);
alert('The background color has changed ' + count + ' times before you clicked me!');
}
interval = setInterval("changeColor()", 2000);
</script>
<style type="text/css">
.Div {
position:absolute;
width: 800px;
height: 100px;
z-index: 15;
top: 50%;
left: 15%;
background: red;
}
</style>
</head>
<body onLoad="setInterval()">
<div id="myDiv" class="Div">
<input type="button" onClick="stop()", value="I like this color" align="absmiddle">
</div>
</body>
</html>