Unable to call a Javascript class from HTML - javascript

Please have a look at the below code
TTSScript.js
function TTS()
{
var msg = new SpeechSynthesisUtterance("yohan");
var voices = window.speechSynthesis.getVoices();
this.speakText = function()
{
window.speechSynthesis.speak(msg);
}
}
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/scripts/TTSScript.js"></script>
<script>
function speak()
{
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
}
function speak2()
{
var TTS = new TTS();
TTS.speakText();
}
</script>
</head>
<body>
<div><button onclick="speak2()">Click me</button></div>
</body>
</html>
Unfortunatly when I click on the button in the html page, what I get is an error. It is below.
Uncaught TypeError: undefined is not a function (13:42:13:817 | error, javascript)
at speak2 (public_html/index.html:23:26)
at onclick (public_html/index.html:31:126)
I am not much familiar with JavaScript, can you please let me know why I am getting this error and how to fix it?

After declaring a function, its name becomes a (locally) preserved word. It means that creating a variable with the same name might cause some problems.
I took your code and changed
var TTS = new TTS();
TTS.speakText();
Into
var tts = new TTS();
tts.speakText();
And the error disappeared.

I solved your problem.. :
don't use all capital names as variables
var tts = new TTS();
tts.speakText();
correct speak call is in the fiddle
http://jsfiddle.net/bpprwfxa/4/
var msg = new SpeechSynthesisUtterance('Yohan');
window.speechSynthesis.speak(msg);

Related

Can't change image source of element ID when using variable name instead of string

I am writing a function to change the src of an image based on two strings passed to the function, a, which is the element ID, and b, which is the new source for the image.
In this instance, I have confirmed that both variables are passed to the function correctly.
console.log(a); is layerAddButton
console.log(b); is images/layerAdd-blue.svg
Here is my code :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
This does not change the url of the image as expected, but gives an error in chrome :
functions.js:3025 Uncaught TypeError: Cannot set properties of null
(setting 'src')
at swapImg (functions.js:3025:32)
at HTMLButtonElement.onmouseleave (app.htm:1132:274)
This works fine when I hard code like so :
document.getElementById('layerAddButton').src = 'images/layerAdd-blue.svg';
I tried it and it works. Make sure to write the Id correctly when passing it to the function. And make sure the script is in the HTML after the element and not in the head.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<img
src="https://www.testingtime.com/app/uploads/2017/07/Grundregeln_fuer_User_Testing-750x500.jpg"
alt=""
id="imgElement"
/>
<body>
<script>
function swapImg(id, url) {
var a = id;
var b = url;
console.log(document.getElementById(a));
document.getElementById(a).src = b;
}
swapImg("imgElement", "https://source.unsplash.com/random");
</script>
</body>
</html>
To fix this, you just needed to pass the variable to the getElementById() function and not just the variable name.
The correct code should be :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}

Access to javascript module Class/object from index.html

I defined Class in my javascript file...I imported that file into html page:
<script type="module" src="./js/controller.js"></script>
How can I now acces to classes inside of that js file?
I want to have something like this (in my html file):
<script>
let app = null;
document.addEventListener('DOMContentLoaded', function () {
//Init app on DOM load
app = new MyApp();
});
</script>
But it doesn't work (I get Uncaught ReferenceError: MyApp is not defined)...If I include this DOMContentLoaded listener into end of my controller.js file, It works. But I lost reference to app variable this way (which I don't want)... Is there way to have reference to something defined in modules?
Most important reason why I want to have that reference is ability to access to my app object from google chrome console...
Thanks!
You can access your class in js file from html in the following way-
My Home.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script type="module">
import { Car } from "./main.js";
let obj= null;
alert("Working! ");
obj = new Car("Mini", 2001);
obj.PrintDetails();
document.addEventListener('DOMContentLoaded', function () {
let obj2 = new Car("Merc", 2010);
obj2.PrintDetails();
});
</script>
</head>
<body>
<h1> Lets try something <br></h1>
</body>
</html>
My main.js file:
export class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
PrintDetails() {
console.log(" Name = "+ this.name);
console.log(" year = "+ this.year);
}
}

Javascript to send notice to discord based on webpage last updated

I'm attempting to create a page that when it's been updated, it sends a notice to a channel in discord. I have a working page with a button that will send a notice to discord(uses webhooks and javascript). I'm stuck on executing use of document.lastModified to detect when the page was last updated so that it can execute the onclick=sendMessage(). Any/all help with this would be appreciated.
-Matt
My code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Discord Webhook Tutorial</title>
</head>
<body>
<button onclick="sendMessage()">Send</button>
</body>
<script>
mess1= document.lastModified;
math=99;
x = hidden(mess1);
if (x == true)
{
function sendMessage() {
var request = new XMLHttpRequest();
request.open("POST", "https://discordapp.com/api/webhooks/736073177125355570/yn5upyFa_7IkqwRXlO9XPzooIyMWkqM7wIXcIjqSR6SlhYD8eBCWOm7vEVl4vmNjQBxL");
request.setRequestHeader('Content-type', 'application/json');
var params = {
username: "Update Bot",
avatar_url: "",
content: "Testing bot... updating..."
}
request.send(JSON.stringify(params));
}
}
</script>
</html>
You will need to store the lastModified value somewhere to be able to compare it.
The only value that you have in the DOM is the current one.
You could do this:
const current = document.lastModified;
// Get the last known modified timestamp
const previous = localStorage.getItem('lastModified');
// Update the current modified timestamp
localStorage.setItem('lastModified', current);
// If they differ, trigger the webhook
if (current !== previous) {
doTheXHRThing();
}

Google chrome is not firing onResult event on voice

Everything is working fine in this code except the result showing part after receiving any audio.Can someone tell me why this is not logging any value in console even after i speak in the headphone.
<!DOCTYPE html>
<head></head>
<body>
<div id="msg"></div>
<div id="msg2"></div>
<script>
(function(){
var reco = new webkitSpeechRecognition();
var msgid = document.getElementById('msg');
reco.interimResults = true;
reco.addEventListener('start',function(){
msgid.innerHTML = 'Listening...';
});
reco.addEventListener('audiostart',function(){
msgid.innerHTML = 'Recording...';
});
reco.start();
reco.onresult = function(e){
console.log(e);
}
})()
</script>
</body>
However, SpeechRecognition() is a constructor which is not supported by most of the browers, if you are running it in firefox, it won't help. Try this code in chrome. Later on in console -> Search for result -> Expand the result tab -> Search something called transcript. There it is, your recorded text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button class="talk">Talk</button>
<h3 class="content"></h3>
<script>
const btn = document.querySelector(".talk");
const content = document.querySelector(".content");
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const myRecognition = new SpeechRecognition();
myRecognition.onstart = function() {
console.log("voice is activated, you may now speak");
};
myRecognition.onresult = function() {
console.log(event);
};
//adding eventListener
btn.addEventListener("click", () => {
myRecognition.start();
});
</script>
</body>
</html>
Internet connection is required for working with speech recognition since the recorded speech must be fed through internet connection to a web service for processing.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API

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');

Categories