Playing audio from characters of a textbox using JavaScript - javascript

I am a complete noob and I have started trying to do a program which plays the sound of each letter's keycode every time it is pressed in the textbox and deletes the text every time I press the Spacebar.
The program clears the textbox when I use the space button, but it doesn't play sound with any character:
<!DOCTYPE html>
<html lang="en">
<head>
<title>keyCode example</title>
<script type="text/javascript">
function showKeyCode(e) {
var letter = e.keyCode
if (letter != 32)
{
var audio = new Audio(e.keyCode + ".wav");
audio.play();
}
else
{
document.getElementById("TextBox1").value = "";
}
}
</script>
</head>
<body>
<input TYPE = text ID="TextBox1" SIZE = 15 onkeyup="showKeyCode(event);">
</body>
</html>

Okay, I found a few problems in your code:
Don't use uppercase tag attributes.
Use quotes for attributes.
Include the <body> tag.
You forgot a semicolon after var letter = e.keyCode.
function showKeyCode(e) {
var letter = e.keyCode;
if (letter != 32) {
var audio = new Audio(e.keyCode + ".wav");
audio.play();
} else {
document.getElementById("TextBox1").value = "";
}
}
I have made a jsFiddle for you. It seems to work.
Furthermore, why do you use onkeyup and not onkeydown?

Related

JavaScript - Why doesn't my code run when "Document.querySelector().value" is outside function + how do I get function to run on input number change?

I would like some help please.
I managed to make my code work after finding a similar question on Stack Overflow, but the method I've been trying previously doesn't seem to work at all.
My code is very simple, if the number is 2 and I click the button, the message will say "Correct". If the number is anything else, it will say "Wrong".
Below is the 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">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<input type="number">
<p>Message</p>
<button>Update</button>
</body>
</html>
Here is the JavaScript code that works
Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
function myFunction() {
const number = document.querySelector("input").value;
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
Here is the code that doesn't work
Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
const number = document.querySelector("input").value
function myFunction() {
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
My question is, why doesn't my second JavaScript code work? Is it possible to keep the number const outside of the function (keep the const variable global)?
As the tutorials I'm watching suggest you keep variables outside functions to prevent DRY.
Also, how can I get the code to run without having to click the "update" button each time
?
e.g. if I type 2, the message will automatically say "Correct".
Thank you very much in advance.
const number needs to be in the function, otherwise the const will be null always
function myFunction() {
const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
Live update on keyup inputfield
const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);

read the word in a dictionary page

I am not a programmer! Anyway; I am working on a dictionary app, I need the user to be able to listen to the word when he clicks (or click a small button next to it). Every word is on its own p tag.
My approach was to give the p tag an id equal to the word,so for the word apple the p id will be id="apple", and the mp3 file name is "apple.mp3".
I need a general script (for the whole page) that grabs the id of the clicked element and push it into an embed inner html function that embeds an audio tag with the src="the clicked id.mp3" and play it.
Here what I was trying, but obviously I am missing the correct syntax
<!DOCTYPE html>
<html>
<head>
<title>Get ID of Clicked Element using JavaScript</title>
</head>
<body>
<button id='cat' >cat</button>
<button id='dog' >dog</button>
<script>
document.addEventListener('click', function(e) {
alert(e.target.id);
});
function playSound(soundfile) {
document.getElementById("the grapped Id").innerHTML=
"<embed src= the grapped id""+soundfile+"\" hidden=\"false\" autostart=\"true\" loop=\"false\" />";
}
</script>
</body>
</html>
Some notes:
Instead of id use data-* as more suitable attribute for such tasks.
Create audio elements using the Audio() constructor.
Keep loaded sounds in the memory to reduce the number of server requests and improve user experience.
<!DOCTYPE html>
<html>
<head>
<title>Click a word to listen it</title>
</head>
<body>
<p data-sound="cat">cat</p>
<p data-sound="dog">dog</p>
<script>
var sounds = {};
function loadSound(name) {
if (sounds[name]) {
return sounds[name];
}
var file = '/sounds/' + name + '.mp3',
sound = new Audio(file);
sound.onerror = function() {
alert('File not found: ' + file);
};
sound.onloadedmetadata = function() {
sounds[name] = sound;
};
return sound;
}
function playSound(name) {
var sound = loadSound(name);
if (sound.currentTime > 0) {
sound.pause();
sound.currentTime = 0;
}
sound.play();
}
document.addEventListener('click', function(e) {
if (e.target.dataset && e.target.dataset.sound) {
playSound(e.target.dataset.sound);
}
});
</script>
</body>
</html>

Image swapping when a variable changes

I have an html page that has one image object.
I am trying to write some JavaScript but something isn't working in the script. I have a piece of script that reads a variable and if the variable 'e' is equal to 1, then one image appears. If 'e' is anything other number then image 2 appears. For now, 'e' is static, but it will be dynamic.
How do you change an image dynamically based off a variable?
Any help is most appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<body onload="changei()">
<img id="im1" src="Images/lion1.jpg" width="100" height="180" style="display:show">
<p> hello</p>
<script>
function changei() {
var e = 0;
changei(e);
// something changed e in e = 0;
change(e);
function changei(e) {
var loc = '';
if (image.src.match("lion1")) {
image.src = "Images/lion1.jpg";
} else {
image.src = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
</script>
</body>
</html>
You can use jQuery to change image source. Your function have e inside, pass it as parameter and you can change the image where you want just by calling the function with the corresponding value.
var e = 1;
changei(e);
// something changed e in e = 0;
changei(e);
function changei(e) {
var loc = '';
if (e==1) {
loc = "Images/lion1.jpg";
} else {
loc = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
Example: You can attach an event to an input, keyup and every time you press a key in that input the image will change based on what you entered.
changei(1); // when entering in page set src
$('#eInput').keyup(function(){ // when something was inserted on input
var e = $(this).val();
changei(e);
});
function changei(e) {
var loc = '';
if (e==1) {
loc = "http://images.math.cnrs.fr/local/cache-vignettes/L256xH256/section1-original-0f409.png";
} else {
loc = "http://www.data-compression.com/baboon_24bpp.gif";
}
$('#im1').attr("src",loc); // change image source
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="eInput" />
<img id="im1" src="Images/lion1.jpg" style="display:show">
You can do two things:
You will be changing value of the variable e in some function then simply create a function to change image as follows and call it.
function changeImg(e){
if(e==1)
//your code for image 1
else
//code for image 2
}
Call this function right after you change e.
Use the setInterval() function. e.g.
setInterval(5000,function(){
changeImg(e);
});
Although, you should keep in mind that you need to make e global for case 2

How to use multiple javascript events in one HTML doc?

I have a page with 2 javascript events, one triggered from the mouse, the other from the keyboard. When I load the page I can get one or the other to work, but not both. If I press a key first that function will run, but then I cannot do the mouse click or another keystroke. And vice versa. I know jQuery makes this easier, but I'd rather not have my users download that for each page, so I'm trying to do this the old fashioned way. I have read as much about javascript events as I can find but I'm stuck here with this one ...
thanks in advance, Brad.
NOTE: in Chrome and Safari I get the above results, Firefox and Opera will only work with the keystroke function
<html>
<head>
<script>
function create(event) {
var x=event.clientX-14;
var y=event.clientY-33;
var output = document.write("<p id=\"text\" style=\"background-color: white; position: absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M#jesty!</p>");
}
function type(event)
{
var letter_in = event.keyCode;
var letter = String.fromCharCode(letter_in);
//var shift = event.shiftKey;
//if (shift === false) {letter = String.toLowerCase;}
document.write(letter);
}
</script>
</head>
<body onmousedown="create(event)" onkeydown="type(event)">
</body>
</html>
It's because you're using document.write() which clears everything else on the page, including your handlers.
Calling document.write() after the document has been loaded implicitly calls document.open(), which clears the document.
So to fix this, you want to use something like innerHTML to only update the contents of an element within your page.
See this example:
<html>
<head>
</head>
<body onmousedown="create(event)" onkeydown="type(event)">
<div id="foo"></div>
<script>
function create(event) {
var x=event.clientX-14;
var y=event.clientY-33;
var output = document.getElementById("foo").innerHTML = "<p id=\"text\" style=\"background-color: white; position: absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M#jesty!</p>";
}
function type(event)
{
var letter_in = event.keyCode;
var letter = String.fromCharCode(letter_in);
//var shift = event.shiftKey;
//if (shift === false) {letter = String.toLowerCase;}
document.getElementById("foo").innerHTML = letter;
}
</script>
</body>
</html>

getElementsByTagName() behaves differently in IE and FF

I am new to JavaScript, trying to figure out a tag information value. GWT Code is as follows..
public static native boolean isToolBarInstalled() /*-{
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
if (metas[i].getAttribute('name') == "toolbar"){
return true;
}
}
return false;
}-*/;
FF return true whereas IE returns false, for the same page? Any clue/suggestions would be helpful.
WM.
HTML is too huge to post, here is a snippet of the code..
<html>
<head>
....
<title>My App</title>
<meta name="toolbar" content="1.0">
</head>
<body>
.....
</body>
<html>
Works for me in IE7.
Check you haven't got any text content before the <meta> end-tag other than simple whitespace.
If you have any non-whitespace text in or before <html> or <head>, the browser will decide that you meant to open the <body> to contain the text. (This is actually valid in non-XHTML HTML, as the </head> end-tag and the <body> start-tag are optional.) That means closing the <head> section, so the number of <meta> tags inside <head> will be 0.
In any case you might as well say just:
var metas= document.getElementsByTagName('meta');
as the bit about checking they're in <head> is redundant for a valid document; that's the only place <meta> is allowed to appear.
alert("Value: "+metas[i].value);
There's no .value on <meta>, do you mean .content?
if (metas[i].getAttribute('name') == "toolbar"){
Use metas[i].name. There's no reason to use getAttribute/setAttribute on an HTML document and there are problems with it on IE.
Try this:
element.attributes[value].nodeAttribute;
As explained here:
The getAttribute() method will return
"null" in Internet Explorer when
trying to get the for attribute of a
label element.
Might be the same issue...
Well look:
Example
Source
In this example it is working on IE.
function isToolBarInstalled() {
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
var attr = metas[i].getAttribute('name');
// IE workaround
if (attr == null)
{
attr = metas[i].attributes["name"];
if (attr != null) attr = attr.nodeValue;
}
if (attr == "toolbar")
return true;
}
return false;
}
alert( "Is installed: " + isToolBarInstalled() );

Categories