Write the text with typing effect using javascript/Jquery - javascript

I will receive some content from server side.What I trying is to make the typing effect at the time of display this content.
$("#dislay").click(function() {
//this is the dummy content i will recieve from server
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typerText = "";
var contentLength = contentFromServer.length;
var count = 0;
var typingSpeed = 100000 / contentLength;
var typer = setInterval(function() {
if (count > contentFromServer.length) { clearInterval(typer); }
typerText += contentFromServer.charAt(count);
document.getElementById("dislayArea").innerHTML = "" + typerText + "";
count++;
}, typingSpeed);
//reset the interval on click of button
$("#dislay").click(function() { clearInterval(typer); });
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="dislayArea"></div>
The question is I do not know if I'm using the correct way or not. That is, not sure if it would be better to use the for loop, or use setInterval(what I am using). Or there is any better approach to do this.

Using setInterval() is definitely better than loop statement, as using loop will block your JS execution and you would not be able to do something during the same time. To avoid this you may use variable speed based on string length (as you have done) but IMO this will not give good visual experience.
I will also suggest to take a look at typed.js library. (There can be other libraries that achieve the same task, but I have experience with this library and it works great!)
Using the library provides more flexible control over the task with various options and again why to reinvent the wheel ?
Here is an example snippet of typed.js:
var typed = null;
$("#dislay").click(function() {
if(typed != null)
typed.destroy();
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typedOptions = {
strings: [contentFromServer],
typeSpeed: 60,
showCursor: false
};
typed = new Typed("#displayArea", typedOptions);
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.8/typed.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="displayArea"></div>

Related

Microsoft Translate Voice limit 200-400 words when request

I have a URL of Microsoft Translate Voice to get voice look like:
<audio controls autoplay>
<source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I’m Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>
The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?
If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:
// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
// Define your DOM elements
var getAudioBtn = document.getElementById('getAudioBtn'),
langSelect = document.getElementById("langSelect"),
langSource = document.getElementById("langSource"),
audioEl = document.getElementById('audioEl');
// Setup an event listener on the button
getAudioBtn.addEventListener('click', getContentTranslate);
// Setup an listener on the audio onended event
audioEl.addEventListener('ended', readChunkQueue);
var chunkQueue = [], // Queue of chunks of text to read
wordsPerChunk = 80, // Words per chunk
language = 'en'; // Default language
function getContentTranslate() {
// Store the language
language = langSelect.value;
// Empty the chunks array
chunkQueue = [];
// Split the text into words
var words = langSource.value.split(/ /g),
tmp = []; // Temporary array for creating a chunk
while(words.length) {
// If out temporary chunk is full, add it to the list
if (tmp.length === wordsPerChunk) {
chunkQueue.push(tmp.join(' '));
tmp = [];
}
tmp.push(words.shift());
}
if (tmp.length) {
chunkQueue.push(tmp.join(' '));
}
// Start reading these chunks
readChunkQueue();
}
function readChunkQueue() {
// If the list is empty, stop
if (!chunkQueue.length) {
return;
}
// Get the first chunk in the list
var chunk = chunkQueue.shift(),
url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
+ '&language=' + encodeURIComponent(language)
+ '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
+ '&text=' + encodeURIComponent(chunk);
// Set the URL as source for the audio element
audioEl.setAttribute('src', url);
}
});
<select id="langSelect">
<option value="en">English</option>
<option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>
<br>
<button id="getAudioBtn">GET AUDIO</button>
<br>
<audio id="audioEl" autoplay controls></audio>

Quotes script not working

I have a script to display random quotes after clicking on button. Please help me understand why it is not working.
function quotes() {
var aquote = new Array;
aquote[0] = "\"Nobody exists on purpose. Nobody belongs anywhere. We're all
going to die.Come watch TV.\"";
aquote[1] = "\"Listen, Morty, I hate to break it to you but what people call
love is just a chemical reaction that compels animals to breed.It hits
hard, Morty, then it slowly fades, leaving you stranded in a failing
marriage.I did it.Your parents are gonna do it.Break the cycle, Morty.
Rise above.Focus on science."\"";
aquote[2] = "\"Weddings are basically funerals with cake.\""
aquote[3] = "\"There is no God, Summer. Gotta rip that band-aid off now
you’ ll thank me later.\""
aquote[4] = "\"I’m sorry, but your opinion means very little to me.\""
aquote[5] = "\"Being nice is something stupid people do to hedge their
bets.\""
rdmQuote = Math.floor(Math.random() * aquote.length);
document.getElementById("quote").value = aquote[rdmQuote];
}
window.onload = quotes;
<marquee><p id="quote"></p></marquee>
You have a syntax error on the aquote[1] line. In the end it should be Focus on science.\""; instead of Focus on science."\"";. Note the third quote from the end.
Once that is fixed, you need to set the innerText of quote, rather than its value. See the working snippet below:
<script>
function quotes(){
var aquote = new Array;
aquote[0]="\"Nobody exists on purpose. Nobody belongs anywhere. We're all going to die. Come watch TV.\"";
aquote[1]="\"Listen, Morty, I hate to break it to you but what people call love is just a chemical reaction that compels animals to breed. It hits hard, Morty, then it slowly fades, leaving you stranded in a failing marriage. I did it. Your parents are gonna do it. Break the cycle, Morty. Rise above. Focus on science.\"";
aquote[2]="\"Weddings are basically funerals with cake.\""
aquote[3]="\"There is no God, Summer. Gotta rip that band-aid off now you’ll thank me later.\""
aquote[4]="\"I’m sorry, but your opinion means very little to me.\""
aquote[5]="\"Being nice is something stupid people do to hedge their bets.\"";
rdmQuote = Math.floor(Math.random()*aquote.length);
document.getElementById("quote").innerText=aquote[rdmQuote];
}
window.onload=quotes;
</script>
<marquee><p id="quote"></p></marquee>
I see a couple problems. First line breaks are messing up where you declare the values. Second, you have an extra " mark on one of the lines. And last, you need to change the innerHTML not the value. Try this instead:
function quotes() {
var aquote = new Array;
aquote[0]="\"Nobody exists on purpose. Nobody belongs anywhere. We're all going to die. Come watch TV.\"";
aquote[1]="\"Listen, Morty, I hate to break it to you but what people call love is just a chemical reaction that compels animals to breed. It hits hard, Morty, then it slowly fades, leaving you stranded in a failing marriage. I did it. Your parents are gonna do it. Break the cycle, Morty. Rise above. Focus on science.\"";
aquote[2]="\"Weddings are basically funerals with cake.\"";
aquote[3]="\"There is no God, Summer. Gotta rip that band-aid off now you’ll thank me later.\"";
aquote[4]="\"I’m sorry, but your opinion means very little to me.\"";
aquote[5]="\"Being nice is something stupid people do to hedge their bets.\"";
rdmQuote = Math.floor(Math.random()*aquote.length);
document.getElementById("quote").innerHTML=aquote[rdmQuote];
}
window.onload=quotes;

Find and repalce text in javascript except in <b></b> in a string [duplicate]

This question already has answers here:
Regex replace text outside html tags
(2 answers)
Closed 7 years ago.
currently to do search and replace string in JavaScript, I am using below code:
var regEX = new RegExp(toFind,"gi");
var newString = oldString.replace(regEx,toReplace);
where OldString contains tons of HTML tags.
What I need to do is during the execution of replace function I don't want the search and replace to be done on text between <b></b> tags.
How can I do this in Js? Is there any other way of doing the replacement?
As a example please consider below string:
<div id="testDiv">
<h2>In on announcing if of comparison pianoforte projection</h2>
<p>Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession the unpleasing simplicity her uncommonly.</p>
<b>Kept in sent gave feel will oh it we. Has pleasure procured men laughing shutters nay. Old insipidity motionless continuing law shy partiality. Depending acuteness dependent eat use dejection. Unpleasing astonished discovered not nor shy. Morning hearted now met yet beloved evening. Has and upon his last here must.</b>
<p>New the her nor case that lady paid read. Invitation friendship travelling eat everything the out two. Shy you who scarcely expenses debating hastened resolved. Always polite moment on is warmth spirit it to hearts. Downs those still witty an balls so chief so. Moment an little remain no up lively no. Way brought may off our regular country towards adapted cheered.</p>
<p><b>Not To be Replaced</b>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under.</p>
</div>
I think, this is what you are looking for:
var re = /[^<b>]*[^<\/b>]/gi;
var str = '<b>Heloo..!,</b>Mr.Its<b>too hot</b>.oops!'
var rstr = str.replace(re,'nooo');
console.log(rstr);// prints <b>nooo</b>nooo<b>nooo</b>nooo

Fade in p tags one by one

Let's say I've got few p tags:
<p>Style never met and those among great. At no or september sportsmen he perfectly happiness attending. Depending listening delivered off new she procuring satisfied sex existence. Person plenty answer to exeter it if. Law use assistance especially resolution cultivated did out sentiments unsatiable. Way necessary had intention happiness but september delighted his curiosity. Furniture furnished or on strangers neglected remainder engrossed.</p>
<p>Not far stuff she think the jokes. Going as by do known noise he wrote round leave. Warmly put branch people narrow see. Winding its waiting yet parlors married own feeling. Marry fruit do spite jokes an times. Whether at it unknown warrant herself winding if. Him same none name sake had post love. An busy feel form hand am up help. Parties it brother amongst an fortune of. Twenty behind wicket why age now itself ten.</p>
<p>For though result and talent add are parish valley. Songs in oh other avoid it hours woman style. In myself family as if be agreed. Gay collected son him knowledge delivered put. Added would end ask sight and asked saw dried house. Property expenses yourself occasion endeavor two may judgment she. Me of soon rank be most head time tore. Colonel or passage to ability.</p>
which are opacity:0 and I want to fade in them, one by one, with delay of, say 350ms.
How would I do that?
All my attempts
$.each($('p'), function(index,element){
setTimeout(function(){ $(element).fadeIn(); }, 350);
});
ended up fading in all p tags in same time.
This should do:
$("p").each(function(index) {
$(this).delay(350*index).fadeOut(300);
});
Try this one:
$("p").each(function(index) {
$(this).delay(350*index).animate({opacity:1});
});
The reason they are all going at the same time is that the timeouts are all set at almost the same time. meaning they will all wait 350 seconds from the time the each is run.
Try this
ps = $('p').toArray();
function fadeNext(ps){
$(ps[0]).fadeIn(350, function(){
ps.shift();
if(ps.length){
fadeNext(ps);
}
})
}
Here is a code snippet with it fading out:
function fadeNext(ps) {
console.log($(ps[0]))
$(ps[0]).fadeOut(350, function() {
ps.shift();
if (ps.length) {
fadeNext(ps);
}
})
}
$('#fade_button').click(function() {
ps = $('p').toArray();
fadeNext(ps);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Style never met and those among great. At no or september sportsmen he perfectly happiness attending. Depending listening delivered off new she procuring satisfied sex existence. Person plenty answer to exeter it if. Law use assistance especially resolution
cultivated did out sentiments unsatiable. Way necessary had intention happiness but september delighted his curiosity. Furniture furnished or on strangers neglected remainder engrossed.</p>
<p>Not far stuff she think the jokes. Going as by do known noise he wrote round leave. Warmly put branch people narrow see. Winding its waiting yet parlors married own feeling. Marry fruit do spite jokes an times. Whether at it unknown warrant herself winding
if. Him same none name sake had post love. An busy feel form hand am up help. Parties it brother amongst an fortune of. Twenty behind wicket why age now itself ten.</p>
<p>For though result and talent add are parish valley. Songs in oh other avoid it hours woman style. In myself family as if be agreed. Gay collected son him knowledge delivered put. Added would end ask sight and asked saw dried house. Property expenses yourself
occasion endeavor two may judgment she. Me of soon rank be most head time tore. Colonel or passage to ability.</p>
<button id="fade_button">try it</button>

Javascript random quote generator NO REPEAT

Please refer to www.thisyeariwantto.com This is the js code I am using to display "random" quotes... but the problem I keep having is that the quotes on the array repeat themselves. I want the user to come in click and click without ever seeing the same quote twice. How can I achieve this? Thank you in advance.
function jargonator(){
$('#head').text("This year I want to...");
$('#tag').text("");
var fragments = shuffle(
["gym","Fall in love(cliche), be happy and work abroad","stop fighting with my boyfriend","to finish things, no matter how long they take or how silly they are", "I'LL FINISH EVERY THING I START !","adopt a Koala","write a book","make a million","grow a pair","get married","drink less live more","figure out where i buried her","Give my girlfriend a real orgasm","Read more books","Save more money","Lose weight","Redecorate","Take better photos so that I can gain more instagram followers","Stop it with the #selfies","Travel","Stop cheating on my husband","Sell old unwanted stuff on eBay","Do something for charity","Get new boobs","Spend more time with kids","Spend Less time on Facebook","Totally revamp my wardrobe","Try a new hairstyle... down there ;)","Have a threesome","Get a six-pack... of premium artisanal beer","Eat less chocolate","Socialise more in real life rather than Facebook","Drink less alcohol","Eat an entire bowl of Ben & Jerrys without feeling guilty", "Start my own business","Recommend this site to all my friends","Tell Susan I have feelings for her","Stop hitting my girlfriend","Do less cocaine","Quit smoking","Get a promotion","stop saying, 'Ooh, that feels nice' whenever the security guys frisk me at airports.","work with neglected children. (my own)","balance my checkbook. (on my nose).","Learn how to use Twitter","Stop sleeping with my brother’s fiancée","Have a better relationship with my parents","do less laundry and use more deodorant","assure my lawyer that I will never again show up drunk at a custody hearing.","start shaving my legs again","Run a half or full marathon","Call people more than text","Stop texting 'LOL'","Stop sexting my cousin", "Watch less reality TV","Stop treating my cat like a real person","Stop buying every iphone that comes out","Stop sleeping with my ex","Stop faking my orgasms","go to the beach more often","get penis reduction surgery so my girl lets me fuck her in the ass","start pretending i'm gay so I can get free drinks at the rainbow room","stop lying on my resume","Exclude McDonald's from my daily diet","Stop considering ketchup a vegetable","stop pretending I have friends","Make at least one REAL friend","Learn how to spell 'thru'... 'thrugh'... 'trhouh'.... fuck it.","Get into a fight so I can finally use my mma skills","stop watching mma so my girlfriend stops thinking I'm gay","Paint my balls blue so I always have an excuse for my gf to jerk me off","Tell Rebecca to fuck off, she is such a bitch","tell my son he is adopted, and his real name is not Kyle... it is Rodrigo.","Stop being a hipster because everyone is doing it","Stop being a hipster, thats so 2013","stop taking naked pictures in snapchat","Reduce, reuse, recycle :)","Graduate!","Be happy!","Take more pictures","Learn how to twerk","stick my tongue out and not feel dirty...like Miley","ride naked on a wrecking ball...with a hammer","make my first legal pornographic movie...with a hidden camera...","learn japanese curse words","star on a rap video as one of the hoes in the back","get my freak on...it's been off way too long...and people are talking","stop showing my boobs so I get more likes","make my momma proud","stop sleeping with my boss's daughter","wear condoms more often","tell him he is not the real dad...","Have intense lesbian sex in public places.","stop making new year's resolutions.","finally dunk.","stop doing Molly","Eat the still beating Heart of Jeff Gordan","get rich doing what i like","Do the splits!","speak up","finally open my own practice","meet a girl","be more positive","Stop being an intern and get a job.","travel to where the soul meets body.","get a tattoo","be fearless","stop curating, start creating", "continue to make my boyfriend happy to the best of my ability.","leave The City and start really living","become a mermaid","Quit 'Call me maybe'","Do my Irish penpal", "Have more bacon, have more sex","study quantum physics so I can RULE THE WORLD","stop biting my nails","drink quality instead of quantity","sleep completely naked in a middle of a peaceful forest","Take a shower with Ryan Gosling","break the circle of no-life", "BOOMSHAKALAKA!!!","Break the Internet", "go back to the future","play hide & seek with strangers on the internet","file a complaint to the Karma Police","NOT fall in love","Stop making a Morgan Freeman voice when talking about Nelson Mandela's death","Make my husband allergic to viagra... i am tired!! :)","cast a worldwide campaign to protest against animal abuse","drink over 20 Mezcal shots in a row","star in the next Star Wars movie","get inspired","stop thinking 'It'll be our year... I'm the only one being the Zombie","Try and see if I can live on wine and sushi... and nothing else","Prove Einstein was wrong","Buy a hammock and work from there","forget about Teen Spirit","find the second star to the right, and go straight on till morning","Leave Narcissus alone","write a novel","make the team","go to all my AA meetings","spit in the face of convention","Somewhere I've never been yet","learn a new recipe", "Paint!", "learn to meditate and at least take one weekend for myself to travel.",]
)
$('#c').click(function () {
change(1000);
});
function change(time){
$('#tag').animate({
opacity: 0
}, time, function () {
$('#tag').html(fragments.pop()).animate({
opacity: 1
}, time)
});
}
function shuffle(o) { //v1.0
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
change(0);
}
I really need help. If you need to see any other code of any of the other files please let me know. thank you very much.
you can just poping it from array
for( var i=0;i<fragments.length;i++){
str += fragments[i].pop();
if(i <fragments.length-1){str+=stub;}
}
if you do so, then it remove quote and you never have dublicates.
and before doing this, you can sort array random, then you will have different quotes every time
something like this.
We cannot control the value returned by Math.random() as you expecting. However try this workaround, every time a value is generated add it to another array, say mylist
var fragments =[
["quote1", "quote2", "quote3","etc", ... ]
var selected;
var temp;
var str = "";
var stub = "";
for( var i=0;i<fragments.length;i++){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
while(selected.contains(temp)){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
}
selected.push(temp);
str += temp;
if(i <fragments.length-1){str+=stub;}
}
$('#tag').animate({opacity:0.9},1000).append(str);
}
Eventually at some time all randoms get generated after that clear mylist and continue. At least random wont repeat until all elements in your fragments get selected once.

Categories