How to get an inscription from a div? - javascript

Hi I wanted to get my inscription "something" and show it on the screen every 2 seconds.
Something doesn't work. Thanks for all help :)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id = "word">something</div>
<script type="text/javascript">
var myVar = document.getElementById("word");
setInterval(function func1(){
document.write(myVar)
},2000);
func1();
</script>
</body>
</html>

Use this
var myVar = document.getElementById("word").innerHTML;

You don't need to run the function manually, setInterval will execute it every 2 seconds.
setInterval(() => {
const word = document.getElementById('word');
const output = document.getElementById('output');
output.innerHTML = word.innerHTML;
}, 2000);
<div id="word">Something</div>
<div id="output"></div>

add innerHTML to extract data from div.
You don't need to name the recurring function.
var myVar = document.getElementById("word").innerHTML;
setInterval(function(){
document.write(myVar);
// alert(myvar);
},2000);
<div id="word">test</div>

Related

Div innerHTML is not updated

I have the following test code and I want to update the div text and show one, two, three... but the result is only the last
Edit: Because any answer here it depends on "sleep", I don't actually use "sleep" on my code. I replaced the code with a for loop.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function dosomething() {
for(i=1; i<=500; i++) console.log(i);
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
dosomething();
document.getElementById("demo").innerHTML = 'two';
dosomething();
document.getElementById("demo").innerHTML = 'three';
dosomething();
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
In your example the system never has a chance to show you the one, two, three because it's tied up looping in your while and the page is not getting repainted.
You need to give it a break!
You can use the JS function setInterval for this - it will run a given function every time interval. But you also need to know when to stop it - and it's not absolutely accurate as there may be other things going on on your system so don't use it for e.g. implementing a stopwatch.
You can also use the JS function setTimeout which runs just the once, and then you run it again etc until you've output all the texts. Here's a small example:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
let text = ['one', 'two', 'three', 'stop'];
let i = 0; //this indicates which text we are on
function test() {
document.getElementById("demo").innerHTML = text[i];
i++;
if ( i< text.length) {
setTimeout(test,1000);
}
}
</script>
</body>
</html>
You might be better off using the in-built setTimeout function, with some tweaks. Something like:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
var contentArray = ['one', 'two', 'three', 'stop']; // <- declare the array of values you want here
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
for(let i = 0; i < contentArray.length; i++){ // <- using 'let' instead of 'var', so a new variable is created on each iteration
setTimeout(function() {
// console.log(i); // <- if you want to see the values, uncomment this line
document.getElementById("demo").innerHTML = contentArray[i];
}, 1000 * (i+1));
};
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
With your self written sleep function, you stopped the Browser from passing the rendering Process until all your code had run.
You have to do something like this:
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function sleep(sleepDurationMS) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, sleepDurationMS);
});
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'two';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'three';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
});
});
});
}
</script>
</body>
JavaScript is Asynchronous so you will Get 'stop' as output .
Here I am using setTimeout Function() .
You don't need sleep function and here.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
setTimeout(function () {document.getElementById("demo").innerHTML = 'one';},1000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'two';},2000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'three';},3000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'stop';},4000);
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
Your sleep function is blocking the Event Loop and this line
$myBtn.style.display = 'none';
causes the text to be hidden.
If you want that sleep feature, you should write it in async manner using Promise with setTimeout like this
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
const sleep = async (sleepDurationMS) => new Promise((resolve) => setTimeout(() =>
resolve(), sleepDurationMS))
async function test() {
let $myBtn = document.getElementById('myBtn');
document.getElementById("demo").innerHTML = 'one';
await sleep(1000);
document.getElementById("demo").innerHTML = 'two';
await sleep(1000);
document.getElementById("demo").innerHTML = 'three';
await sleep(1000);
document.getElementById("demo").innerHTML = 'stop';
}
</script>
</body>
</html>

How can I make a variable be the select Id in a getElement

How can I make a variable be the select Id in a getElement? When I tried it, it returned null. My code is shown below:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body
</html>
That code seems to work just fine (with the exception of the unclosed body tag), here is a runnable version of the code, fixed:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
document.getElementById(test).innerHTML = "complete";
</script>
</body>
</html>
Remember, the js code is going to happen almost immediately, so you won't be able to see the "hi" part. If you want it to change after like 1 second, use this:
<html>
<head>
</head>
<body>
<p id = "test">hi</p>
<script>
var test = "test";
setTimeout(function () {
document.getElementById(test).innerHTML = "complete";
}, 1000);
</script>
</body>
</html>
All I changed in that, is put the document.getElementById() into a setTimeout
Hope this helped.

Simple javascript for a clock not working

Hi this is my first javascript and it is not working. The script is programmed to display a clock. The code is as follows:
<html>
<head>
<script type="text/javascript" src="clock.js" > </script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
The javascript is :
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
When execute I get a blank screen. What and where is the mistake ?
TIA :)
You should probably be consistent with ending lines in semi-colon. Also, you should check that clock.js is loading; finally put the onload handler in quotes like
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
tt = display_c();
}
<html>
<body onload="display_ct();">
<span id='ct'></span>
</body>
</html>
Please enclose your onload attribute value of body tag inside " " .
It should be
<body onload="display_ct();">
Try using setInterval(), also this line won't work in some browsers:
setTimeout('display_ct()',refresh)
var ct;
function display_c() {
//timer block
setInterval(function() {
ct.innerHTML = new Date().toString();
}, 1000); //execute every 1 second
}
function display_ct() {
ct = document.getElementById('ct'); //initialize once.
display_c();
}
<!-- onload, enclosed in quotes -->
<body onload="display_ct()">
<span id='ct'>Loading ...</span>
</body>
You made two errors when entering the display_ct function. You needed to wrap the <body>'s onload event with quotes, and remove the quotes and the parentheses on the setTimeout. See below.
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout(display_ct, refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
display_c();
}
<html>
<head>
<script type="text/javascript" src="clock.js">
</script>
</head>
<body onload="display_ct()">
<span id='ct'></span>
</body>
</html>

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

Javascript variable access in HTML

Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>
Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ
The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>

Categories