Run ResponsiveVoice speech on page load - javascript

This works properly, it speaks the text area on click, but how can I change it to speak onload?
<script src="http://responsivevoice.org/responsivevoice/responsivevoice.js"></script>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<textarea id="text" cols="45" rows="3"> HHHH</textarea>
<select id="voiceselection"></select>
<input onclick="responsiveVoice.speak($('#text').val(),$('#voiceselection').val());" type="button" value="Play" />
<br>
<button id="isPlaying">Playing:</button>
<p id="r">?</p>
Text area just says four letters now.
I imagine this is the key part, but can not fit it into anything properly to execute:
responsiveVoice.speak($('#text').val(),$('US English Female').val());
I tried:
var voicelist = responsiveVoice.getVoices();
var vselect = $("#voiceselection");
$.each(voicelist, function() {
vselect.append($("<option />").val(this.name).text(this.name));
});
// Yours
$('#isPlaying').on('click', function() {
$('#r').text(window.speechSynthesis.speaking)
})
$(document).ready(function() { //short code: $(function() { ... });
responsiveVoice.speak($('#text').val(), $('US English Female').val());
});
<script src="http://responsivevoice.org/responsivevoice/responsivevoice.js"></script>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<textarea id="text" cols="45" rows="3">It reads this</textarea>
<select id="voiceselection"></select>
<script>
</script>
<input onclick="responsiveVoice.speak($('#text').val(),$('US English Female').val());" type="button" value="Play" />
But I get a "No voice found for: undefined" error.

Hook into the OnVoiceReady handler, then try to speak once the default voice, etc. is loaded:
responsiveVoice.OnVoiceReady = function() {
console.log("speech time?");
responsiveVoice.speak($('#text').val());
};
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//responsivevoice.org/responsivevoice/responsivevoice.js"></script>
<textarea id="text" cols="45" rows="3">one two three</textarea>

Thanks for using ResponsiveVoice!
You should attach to the OnReady event using this code:
responsiveVoice.addEventListener("OnReady", myInitFunction);
as it's not enough to wait until page load. You need to wait until voices are loaded.
why wont this run on iphone safari?
Apple prevents any speech to be initiated without a user action. So you would need to trigger speak() after a button click, for example.
also why does it stop working after after 4 or 5 refresh after 10
seconds on android broswer?
ResponsiveVoice has some issues on Android devices. We're working on fixing it. We recommend using our latest release which you can find here:
https://code.responsivevoice.org/develop/responsivevoice.js

Don't use inline event handling. Use abstracted events. It makes for easier to understand/read code.
$(document).ready(function() { //short code: $(function() { ... });
responsiveVoice.speak($('#text').val(),$('#voiceselection').val());
});
The document ready event is triggered when the DOM is finished loading.
No jQuery version:
window.onload, using the new ES6 standard arrow function. No jQuery needed!
window.onload = () => {
responsiveVoice.speak(document.getElementById("text").value, document.getElementById("voiceselection").value);
}

According to the official site, the second argument must be a valid voice type, but in your example, the element voiceselection has no values, then the API fails. If you try with the default voice, the API will succeed!
var text = $('#text').val(),
voice = $('#voiceselection').val();
//success
responsiveVoice.speak(text); //HHHH
//fails
responsiveVoice.speak(text, voice); //HHHH, ""
//Uncaught TypeError: Cannot read property 'mappedProfile' of null(…)

Related

Mimic 'Paste' function into Input Text

I have an <input type=text> that wants user to paste a URL into it. However, I want the site to provide a default URL in it, but changing the value isn't enough-- the site needs to mimic the paste event as if the user pasted the default URL in themselves.
So, is there a way to pseudo-paste a URL into an input text using jQuery? In the example code I have it so when user pastes an alert 'Hi' pops up, but what I want is when I hit play in the JSFiddle (or load the site in other words) there will be www.example.com pasted in (via the code) and 'Hi' will come up automatically in response.
https://jsfiddle.net/9c47r2qt/1/
$("#test").bind("paste", function() {
alert('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" value="This is some default text" />
Edit: To be clear, I do not want data from the User's clipboard; in fact that would ruin things. I want the site to act as if the code is pasting data.
You can simply use .val() function to assign a default value or paste (Current URL) when the site loads. It will show an alert Pasted the default URL
In your paste function you can use .on instead of .bind (its deprecated now). When the user actually paste something the alert shows User Pasted Something
To get the default current URL you can use window.location.href function.
Run snippet below to see working.
$(document).ready(function() {
//Load the default URL
$('.myInput').val(window.location.href)
//Alert on load
alert('Pasted the default URL')
//Paste function - User
$("#test").on("paste", function() {
alert('User Pasted Something');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" />
Just trigger() the paste event to run the event handler.
$("#test").on("paste", function() {
console.log('New value pasted:', this.value);
}).val('some new string').trigger('paste');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" />

Cannot read property 'addEventListener' of null at dice.js:5

I'm trying to implement a function that will create new divs inside another div based on the number typed by user.
I wanted to do this with addEventListener to the input and ran a test to check if it even works. But it doesnt and I dont know what im doing wrong. Here is my HTML code:
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber">
</form>
and JS part:
var numInput = document.querySelector("input");
numInput.addEventListener("change", function(){
alert("test");
});
How are you including your javascript file in the html document? It may be possible that your JS code is being executed before the html is loaded.
It is hard to answer only with these 2 snippets.
My guess is that you have something like
<html>
<head>
<script>
var numInput = document.querySelector("input");
numInput.addEventListener("change", function(){
alert("test");
});
</script>
</head>
<body>
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber">
</form>
</body>
</html>
In this case, the script will be executed before the dom is loaded which is why the code cannot find the input.
you either have to wait that the dom is ready or move the script block after the definition of the input.

Call a function with the enter key in all browsers

I’ve been trying to make the enter key call a function for a specific text field. Getting it to work with IE is no problem.
Chrome and Firefox are another story, they trigger another function. The code on the text box is:
<input name="Phone" type="text" onkeydown="if (event.keyCode==13 || event.keyDown==13 || event.charCode==13){get2();preventDefault();}">
The code for the function called instead is:
<script type="text/javascript">
$(function() {
$(".button").on("click",function(e) {
e.preventDefault();
location=this.id+".php?"+$('form[name="reportform"]').serialize();
});
});
</script>
I tried modifying that function to:
<script type="text/javascript">
$(function() {
$(".button").on("click",function(e) {
if (event.keyCode==13 || event.keyDown==13 || event.which==13){get2();e.preventDefault();
}else{
e.preventDefault();
location=this.id+".php?"+$('form[name="reportform"]').serialize();}
});
});
</script>
I even tried swapping that function out for:
<script type="text/javascript">
$('#reportform').submit(function(e){
get2();
e.preventDefault();
return false;
});
</script>
I found (keyCode, keyDown, charCode)==13 though numerous google searches and most of the functions on this site, but I have not been able to get it to work. Any insight would be appreciated.
I have tried similar approaches that you describe, for the task, but I have found a better way to deal with it. Simply use forms (and hide the submit button if desired).
<form onsubmit="myFunction();return false;">
<input type="text">
<input type="submit" style="display:none">
</form>
[Enter] key will then cause the form to be submitted, i.e your function to be invoked.
JSFiddle example

How can I set focus on an element in an HTML form using JavaScript?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
window.onload is to put focus initially
onblur is to put focus while you click outside of the textarea,or avoid text area
blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
If your <input> or <textarea> has attribute id=mytext then use
mytext.focus();
function setFocusToTextBox() {
mytext.focus();
}
<body onload='setFocusToTextBox()'>
<form>
<input type="text" id="mytext"/>
</form>
</body>
this example worked for me
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Try This:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
Thought of sharing some edge cases for this subject.
If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result.
Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input

alert when user attempts to enter key into textbox

So I've been searching for a bit now for code that will alert a user with a message (I know how to do an alert) when they try to enter any sort of text into a blank textbox.
Here is my code. What do I add to cause the sendMsg() function to be called?
<script>
function sendMsg()
{
alert ("change msg content here");
}
</script>
here is the HTML:
<body>
<input type="text" name="">
</body>
This might work:
<input type="text" name="foo" onKeyUp="sendMsg()" />
i.e. if I understood your question.
Cheers.
Use the onchange event.
<input type="text" name="" onchange="inputChanged();">
Have you tried giving your input an ID:
<input id="testing" type="text" name="" />
And then your javascript would be:
document.getElementById('testing').onfocus = function() {
// alert("change msg content here");
}
The first thing you'll need to do is attach an event listener to the focus event of the text box (which is triggered when you "focus" on a text box), to do that you'll need some way of locating it in the DOM. The simplest way to do that would be to add an id attribute like so:
<body>
<input type="text" name="" id="msgContent">
</body>
Now you can use the document.getElementById method to find the element:
var textBox = document.getElementById('msgContent');
Then you can attach an event listener:
textBox.addEventListener('focus', function () {
alert('change msg content here');
});
Keep in mind that the addEventListener method isn't available in some older versions of IE, instead there are other fallbacks which are detailed here.
Finally if you're using a library like jQuery, YUI, etc you normalize the browser differences for attaching event handlers:
//jQuery example
$('#msgContent').on('focus', function () {
alert('change msg content here');
});

Categories

Resources