How to type text in HTML - javascript

I'm looking to get the HTML page to type out some text when you visit said page, as if someone behind the screen was using a keyboard even though no one is. I understand this may require the use of the <script> tag.
What I have so far
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">>
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center></p>
<script language=JavaScript>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.all["nothing"].innerHTML = text1; //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script language="JavaScript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>
For whatever reason, I can't get this to work and I can't establish why ._. I've been looking it over for a good few hours now.

your code have some errors for example:
setTimeout(writetext,34)
//count =0 inside the function make an non ending loop
i modified your code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Happy Valentine</title>
<script>
msg1 = "Blah blah with html";
msg2 = " Blah with html";
count = 0;
count2 = 0;
function writetext() {
if (count < msg1.length){
document.getElementById("text").innerHTML += msg1.charAt(count);
count++;
setTimeout(writetext, 50);
}
else {
if (count2 < 14){
document.getElementById("text").innerHTML += msg2.charAt(count2);
count2++;
setTimeout(writetext, 50);
}
}
}
</script>
</head>
<body>
<button onclick="writetext()">Click me</button>
<p id="text"></p>
</body>
</html>

You can use this code and adapt it to what you need.
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla. af \n af';
var speed = 50;
document.onload=typeWriter()
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i).replace("\n","<br>");
i++;
setTimeout(typeWriter, speed);
}
}
</script>
</body>
</html>
And your original code, tweaked to work:
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center id="printto"></p>
<script>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html \n Nextline";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.getElementById("printto").innerHTML = text1.replace("\n","<br>"/*seamles neqlining*/); //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script>
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>

Related

How to create a JavaScript loop to display an output 100 times

I’m doing an exercise for high school. The exercise is to create an input and the input needs to be displayed 100 times ( 1) input 2) input 3) input, etc..) and you are not allowed to do it manually; you need to create a loop.
This is what I have so far. I tried googling it for an hour, but I didn't find anything.
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var str = something;
showReply("output", reply);
}
var something = [
[var text = "";]
[var i;]
[for (i = 0; i < 5; i++) {]
[reply += i + ")" + textFromUser;}]
]
</script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output"></span> </p>
</body>
</html>
How can I do it?
You can create an element and append to your output container using a for loop. Try this:
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
let container = document.getElementById(id);
let p = document.createElement('p');
p.textContent = reply;
container.appendChild(p);
}
function reply(){
var textFromUser = getText("myTextField");
for(let i = 0; i < 100; i++){
showReply("output", textFromUser);
}
}
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <div id="output"></div> </p>
Variable i is used as a counter. If you want to change how many times it loops, just change the i<=num.
for (var i=1; i<=100; i++){
show_reply();
}
I suggest you to check this post on W3Schools.
I've made two files, one for HTML and the other for JavaScript.
Here is the JavaScript code:
function getText(id) {
let text = document.getElementById(id).value;
return text;
}
function showReply(id, reply) {
document.getElementById(id).innerHTML = reply;
}
function reply() {
let textFromUser = getText("myTextField");
let i;
let span1 = document.getElementById("output")
let usert = ""
for (i = 0; i < 100; i++) {
usert += "<br>" + textFromUser
}
span1.innerHTML = usert
}
Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script src="main.js"></script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output">dd</span> </p>
</body>
</html>
There are many different potential solutions for this type of question. Choose the flavor you like and put your own spin on it.
function showReply(id, reply){
document.getElementById(id).innerHTML = reply.join('<br>');
}
function reply(){
var textFromUser = getText('myTextField');
var outputs = [];
for (let i = 0; i < 100; i++){
outputs.push(`#${ i } ${ textFromUser }`)
}
showReply('output', outputs);
}

Simple Typing game (JavaScript)

I am trying to create a typing game that allows users to input the correct alphabets for the word displayed on the screen. If any wrong alphabet is used as input the game won't show a new word until all the alphabets are correctly provided as input. What I am not able to figure out is how I do match multiple characters with Array elements. Here is my code sample.
var p = document.getElementById('word');
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
function keyboardEventsHandle(e){
p.append(e.key);
if(e.key=='a')
{
alert('You typed A');
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3> america </h3>
<script src="javas.js"></script>
</body>
</html>
var p = document.getElementById('word');
var word = document.getElementById("toType")
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
var gameRunning = true
var charIndex = 0;
var wordIndex = 0;
function keyboardEventsHandle(e){
// If you use append here. Every character gets printed out
// p.append(e.key);
if(e.key==wordsList[wordIndex].charAt(charIndex) && gameRunning)
{
// If you use append here only correct characters get printed out
p.append(e.key)
alert('Correct!');
if (wordsList[wordIndex].length == charIndex + 1) {
// Defines which word should get controlled
if (wordsList.length == wordIndex + 1) {
gameRunning = false;
alert('Done');
} else {
wordIndex++;
charIndex = 0;
word.innerHTML = wordsList[wordIndex];
p.innerHTML = "";
}
} else {
// Defines which character of the word should get controlled
charIndex++;
}
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3 id="toType"> america </h3>
<script src="javas.js"></script>
</body>
</html>
You can create a list of elements to match and then do something like this:
const wordsList = ['america','japan','italy','jordan','turkey'];
const listToMatch = ['america','japan'];
let trueOrFalse = listToMatch.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //true
var anotherList = ['america', 'India'];
trueOrFalse = anotherList.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //false

Highlight with color all words which starts with uppercase letter using Javascript

I'm newbie in Javascript and jQuery. I have a text inside a paragraph. I want to highlight with yellowgreen color all words which starts with uppercase letter.
Here is my source code. But it does not works properly.
<!DOCTYPE html>
<html>
<head>
<style>
.mycls {background-color:yellowgreen}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var str = $(p).text();
words = str.split(' ');
for (var i = 0; i < words.length; i++) {
var w = words[i].split('');
if (w.charAt(0) === w.charAt(0).toUpperCase()) {
$(this).addClass("mycls");
}
// words[i] = letters.join('');
}
});
</script>
</head>
<body>
<p>President of USA Barack Obama is ...</p>
</body>
</html>
Thank you to all!
$('p').each(function(){ // to each <p>
r = /[A-Z]\w*/g; // big letter with word symbols, global search
function f(x){
return '<span class="y">'+x+'</span>' // rewrited
}
h = $(this).html(); //get
h = h.replace(r,f); //replace
$(this).html(h); //set
}) //done
.y {
background-color: yellowgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>President of USA Barack Obama is ...</p>
Try this :
<p>President of USA Barack Obama is ...</p>
<style>
.highlighted
{
background-color: yellow;
}
</style>
<script>
var split = $('p').text().split("");
var upperCase= new RegExp('[A-Z]');
$.each(split,function(i)
{
if(split[i].match(upperCase))
{
$('p').html($('p').html().replace(split[i],'<span class=\"highlighted\">' + split[i] + '</span>'));
}
});
</script>
Example : https://jsfiddle.net/DinoMyte/zhu7j8o6/5/

limit click button in html

I am trying to limit a button that can be clicked only 5 times to add radio button. After 5 times adding radio button, it will be disabled. What is the javascript code for this matter? I only able to disable it once after it is clicked. Below is the code
html
<input type ='button' id="id" onClick="a();">
<div id='a'></div>
javascript
function a(){
document.getElementById('a').innerHTML += "<input type='radio'>";
document.getElementById("id").disabled=true;
}
Place a global counter and play with it
var counter=0;
function a(){
if(counter<5){
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++;
}
else{
document.getElementById("id").disabled=true;
}
}
A global variable for amount of times clicked will work:
var clicked = 0;
function a(){
document.getElementById('a').innerHTML += "<input type='radio'>";
clicked++; //increment
if (clicked == 5)
document.getElementById("id").disabled=true;
}
try this:
var counter = 1;
function a(){
if(counter >= 5) {
document.getElementById("id").disabled=true;
return false;
}
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++
}
This is what you need:
var counter = 0;
function a ()
{
if (counter++ < 5)
document.getElementById('a').innerHTML += "<input type='radio'>";
else
document.getElementById('id').disabled = true;
}
You can count the radio buttons
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Add 5</title>
<style>
input[disabled]{text-decoration:line-through;color:white;}
</style>
<script>
function add5(){
var radio,
btn= document.getElementById('add_radio'),
pa= document.getElementById('radioDiv'),
R= pa.querySelectorAll('[type=radio]');
if(R.length<5){
radio= document.createElement('input');
radio.type='radio';
pa.appendChild(radio);
}
else btn.disabled= 'disabled';
}
</script>
</head>
<body>
<p>
<input type ='button' id="add_radio" value="Add Radio"onClick="add5();">
</p>
<div id='radioDiv'></div>
</p>
</body>
</html>

How to I retrieve a current value of textarea ? which method instead of $("form").submit(function(){ can be used?

This is my code:
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="/Perl1/codemirror.css"/>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
problem : so I have alert the value of text area by:
var source = document.getElementById('source').value;
alert(source);
but the value of text area is alert is load at the time of page load.and I want to alert current value of textarea.
I have also tried this:
$("form").submit(function())
but that also not useful.
How can I do this?
you can use
$("#source").val();
Try to use
$("#source").val() to get value of textarea
Thanks
I suppose your problem might be occuring because of the Editor you are using.
http://codemirror.net/doc/manual.html
You should be able to retrieve the value with:
editor.getValue()

Categories