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>
Related
I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>
You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver
I'm making some tests for using (or not) web components in a single page app I'm creating.
Here's an example for the problem:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<template id="aTemplate">
<div style="border:1px solid red">
<p>text <input type="text"></p>
<button>ClickMe</button>
</div>
</template>
<script>
var Proto = Object.create(HTMLElement.prototype);
Proto.createdCallback = function () {
var t = document.querySelector('#aTemplate');
var clone = document.importNode(t.content, true);
this.createShadowRoot().appendChild(clone);
};
Proto.aFunction = function() {
alert("proto " + "text value?");
}
document.registerElement('x-proto', {prototype: Proto});
var ProtoChild = Object.create(Proto);
ProtoChild.createdCallback = function () {
Proto.createdCallback.call(this)
};
ProtoChild.aFunction = function() {
alert("child " + "text value?");
}
document.registerElement('x-proto-child', {
prototype: Proto
});
</script>
<x-proto></x-proto>
<x-proto-child></x-proto-child>
</body>
The problem is that I cannot find a way to set a "onclick" handler in the button (inside the template) that calls the method "aFunction" in the object created using the prototype. The method should be called in the correct object instance, with access to the internal DOM components, and the attributes and functions in the prototype.
I've tried a lot of things, (binding the event after construction, using JS or JQuery, using the created/attached callbacks, a ) but I'm out of ideas.
Thanks in advance.
EDIT:
Thanks to MinusFour for the answer. The line:
clone.querySelector('button').addEventListener('click', this.aFunction);
in what I was trying to do, anyway, resulted in (same but with JQuery, for testing compatibilitiy):
$(this.showButton).on("click", this.aFunction.bind(this));
The "bind" makes 'this' AKA the container, the complete component, available in JS code, what I needed.
Here's the completed final example, someone may find it helpful:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<template id="aTemplate">
<div style="border:1px solid darkgray;padding:10px;margin: 10px;">
<h2 class="theCaption"></h2>
<p>text <input class="theText" type="text"></p>
<button class="showButton">Show val</button>
<button class="closeButton">Close</button>
</div>
</template>
<script>
// The .bind method from Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
function createProto() {
$("#spawnPoint").append("<x-proto x-caption='proto'></x-proto>");
}
function createChild() {
$("#spawnPoint").append("<x-proto-child x-caption='a child of proto'></x-proto-child>");
}
var Proto = Object.create(HTMLElement.prototype);
Object.defineProperty(Proto, "x-caption", {value: "no caption"});
Proto.createdCallback = function () {
var t = document.querySelector('#aTemplate');
var clone = document.importNode(t.content, true);
this.shadowRoot = this.createShadowRoot();
this.shadowRoot.appendChild(clone);
$(clone).children("div").append("<p>ssss</p>")
this.showButton = this.shadowRoot.querySelector('.showButton');
this.closeButton = this.shadowRoot.querySelector('.closeButton');
this.shadowRoot.querySelector('.theCaption').textContent = $(this).attr("x-caption");
this.theText = this.shadowRoot.querySelector('.theText');
$(this.showButton).on("click", this.aFunction.bind(this));
$(this.closeButton).on("click", this.close.bind(this));
};
Proto.aFunction = function () {
alert("in proto = " + $(this.theText).val());
}
Proto.close = function () {
$(this).detach();
}
document.registerElement('x-proto', {prototype: Proto});
var ProtoChild = Object.create(Proto);
ProtoChild.createdCallback = function () {
Proto.createdCallback.call(this);
};
ProtoChild.aFunction = function () {
alert("overrided in child = " + $(this.theText).val());
}
document.registerElement('x-proto-child', {
prototype: ProtoChild
});
</script>
<button onclick="javascript:createProto()">Create proto</button>
<button onclick="javascript:createChild()">Create child</button>
<div id="spawnPoint">
</div>
</body>
I believe you could just add the listener from the importedNode (clone in your case).
clone.querySelector('button').addEventListener('click', function(){
//code logic here
});
You also probably meant:
document.registerElement('x-proto-child', {
prototype: ProtoChild
});
Here's how it would look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<template id="aTemplate">
<div style="border:1px solid red">
<p>text <input type="text"></p>
<button>ClickMe</button>
</div>
</template>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.14/webcomponents.min.js"></script>
<script>
var Proto = Object.create(HTMLElement.prototype);
Proto.createdCallback = function () {
var t = document.querySelector('#aTemplate');
var clone = document.importNode(t.content, true);
clone.querySelector('button').addEventListener('click', this.aFunction);
this.createShadowRoot().appendChild(clone);
};
Proto.aFunction = function() {
alert("proto " + "text value?");
}
document.registerElement('x-proto', {prototype: Proto});
var ProtoChild = Object.create(Proto);
ProtoChild.createdCallback = function () {
Proto.createdCallback.call(this);
console.log(this.template);
/*this.template.querySelector('button').addEventListener('click', function(){
console.log('child');
});*/
};
ProtoChild.aFunction = function() {
alert("child " + "text value?");
}
document.registerElement('x-proto-child', {
prototype: ProtoChild
});
</script>
<x-proto></x-proto>
<x-proto-child></x-proto-child>
</body>
I had a similar issue, a while back:
http://www.davevoyles.com/accessing-member-functions-in-polymer/
Are you using Polymer at all, or just Web Components?
As long as you wrap the functions you are trying to call in the polymer-ready event, you should be good to go, and can call functions from your polymer-element.
Polymer parses element definitions and handles their upgrade
asynchronously. If you prematurely fetch the element from the DOM
before it has a chance to upgrade, you’ll be working with a plain
HTMLElement, instead of your custom element.
Alternatively, you can query for a custom element however you want (via ID, class, attr, or element name) and get the same thing. Here’s his example: http://jsbin.com/qikaya/2/edit
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>
i'm beginner in jQuery Plugin's coding.
I've coded a plugin to generate a Gantt's calendar but i can't succeed with interacting with it.
The code is too long to be posted so i've coded a sample of what a need in kind of interaction.
Here is a sample code that generate a counter and two buttons to increase or decrease the value of the counter.
So the question is : How can i make the button increase / decrease the counter and of course refresh display.
Thanks,
[EDIT]
I explain again what i want to do :
- The buttons are generated by the plugin.
- When they are clicked, they increase/decrease the value and refresh display
- I dont want an external action binding.
- The plugin must be standalone
[/EDIT]
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<link rel="stylesheet" href="/styles/jquery-ui.css" type="text/css">
<script src="/scripts/jquery.js"></script>
<script src="/scripts/jquery-ui.js"></script>
<script>
(function($){
$.fn.mySample = function() {
var _myCount = 0;
this.initialize = function ()
{
this.html('<input type="button" value="--">Count : ' + _myCount + '<input type="button" value="++">');
}
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Sorry for my first answer :)
So here is your mySample plugin working as a standalone
http://jsfiddle.net/P4p3m/2/
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<script src="jquery-1.11.0.min.js"></script>
<script>
(function($){
$.fn.mySample = function() {
this._counter = 0; // Your counter
this.initialize = function (config)
{
// Get the context of the outside
var context = this;
// Init the -- button
var inputMinus = document.createElement("input");
inputMinus.type = "button";
inputMinus.value = "--";
$(inputMinus).click(function(){
context.updateCounter(-1);
});
this.append(inputMinus);
// Init the display
var spanDisplay = document.createElement("span");
context.spanDisplay = spanDisplay;
$(spanDisplay).text(context._counter);
this.append(spanDisplay);
// Init the ++ button
var inputPlus = document.createElement("input");
inputPlus.type = "button";
inputPlus.value = "++";
$(inputPlus).click(function(){
context.updateCounter(+1);
});
this.append(inputPlus);
}
// Updating the counter value and the display
this.updateCounter = function(nbr){
this._counter += nbr;
$(this.spanDisplay).html(this._counter);
};
// Start the plugin
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
I modified your code to add id's to better identify the buttons and a span to identify where we want to modify the count:
Here's the updated code to reflect your comments, along with the code working in a fiddle: http://jsfiddle.net/XMgz4/
(function ($) {
$.fn.mySample = function () {
var _myCount = 0;
var inputStr = '<input id="decButton" type="button" value="--">'
+ 'Count : <span id="count">' + _myCount
+ '</span><input id="incButton" type="button" value="++">';
this.html(inputStr);
this.find("#decButton").on("click", function() {
_myCount --;
$("#count").text(_myCount);
});
this.find("#incButton").on("click", function() {
_myCount ++;
$("#count").text(_myCount);
});
}
})(jQuery);
You will need to put the Count : ' + _myCount + ' inside an element.. like this:
'Count : <div id="result">' + _myCount + '</div>'
After that you will create a function to get the value of result.. like this $('#result').html()
and increase or decrease the value using onclick event of your inputs... (You must to add class or id for your inputs...)
I will suppose that the id is btnDecrease and btnIncrease... You will need to do something like this:
$('#btnDecrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) - 1);
});
and
$('#btnIncrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) + 1);
});
Hope it helps
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");