I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
Related
I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>
I have looked for duplicate questions, however many refer to adding data to XML
please forgive me if I have missed something here but I need some help
so far I have this:
html page
<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>
<p id="content"> Content </p>
</body>
</html>
controlpanelAdmin.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
controlpanelModerator.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
When the page loads, 'Admin Control Panel' is written into the fieldset tag
but is then replaced by: 'Moderator Control Panel'
I cannot for the life of me think how to append both lines (and maybe other data as well) into one element
When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'
That can't happen. Admin Control Panel should never appear in the page.
script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload.
script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
The page finishes loading
The load event fires
The function defined in script/controlpanelModerator.js is called
Don't assign values to window.onload. Use addEventListener instead.
addEventListener("load", function () { ... });
You've got two onload functions competing. Can you merge them into one function?
I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>
An extremely simple question but I am noob. I have been learning javascript and jquery for a while on jsfiddle, there everything works fine, building cool quizzes and all, but when I tried to actually create a directory, reference the jquery library and my javascript file, nothing works, even the below code, when saved as an HTML file doesn't work. I just paste it into notepad and save it as html, when I open it with it doesn'T work.
<html>
<head>
<title>webpage</title>
<script type="text/javascript">
window.onload = function() {
var myDiv = document.getElementById('#div');
myDiv.appendChild(document.createTextNode("Hi my name is Mehmetcan"));
}
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>
Use this as starting point:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>webpage</title>
<script type="text/javascript">
$(document).ready(function () {
var myDiv = document.getElementById('myDiv');
myDiv.appendChild(document.createTextNode("Hi my name is Mehmetcan"));
});
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
Another approach that doesn't rely on JQuery but on pure, vanilla javascript.
<html>
<head>
<title>webpage</title>
<script type="text/javascript">
document.body.onload = loadSite;
function loadSite() {
var newDiv = document.createElement("span");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent);
myDiv.appendChild(newDiv);
}
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>
You can find the full javascript sample as well as more information here, on the document.createElement MDN pages.
document.body.onload = addElement;
var my_div = null;
var newDiv = null;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
I am trying to build a HTML, CSS and jQuery (not just JavaScript) editor, and show the rendered content in an iFrame. Although adding HTML, CSS part is easy, I am unable to execute the JavaScript part.
var html = ""; // HTML code
var content = $("#preview").contents().find("body"); // iframe id is 'preview'
content.html(html);
var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
var head = $("#preview").contents().find("head");
head.append(cssLink);
var js ='<script>'+jsEditor()+'<\/script>' ;
// following part is not working
var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
$content.find('body').append(js );
I am able to execute to core JavaScript using window.eval(), however it is not working for any JS library included, e.g. jQuery etc.
I think your only problem here is your variable naming:
var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
$content.find('body').append(js );
should be ($content ==> content)
var content = $('#preview').contents();
content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
content.find('body').append(js );
I modified your script slightly but only to provide some pre-canned values for html, csVal and a result from jsEditor().
This worked for me in Chrome, Safari & Firefox running off a server on localhost:
HTML:
<html>
<head>
</head>
<body>
<div>Look at your new iFrame</div>
<iframe id="preview"></iframe>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</body>
</html>
Code (also in the html body):
$(document).ready(function() {
var html = "<div>Hello from iframe</div>"; // HTML code
var content = $("#preview").contents().find("body"); // iframe id is 'preview'
content.html(html);
var csVal = "div { color: red; font-size: 40px;}";
var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
var head = $("#preview").contents().find("head");
head.append(cssLink);
var jsCode = "alert('you are in the iframe')";
var js ='<script>'+jsCode+'<\/script>' ;
// following part is not working
var content = $('#preview').contents();
content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
content.find('body').append(js );
});
Resulting source in the iFrame:
<html>
<head>
<style>
div {
color: red;
font-size: 40px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div>Hello from iframe</div>
<script>
alert('you are in the iframe')
</script>
</body>
</html>