javascript array only works when not completely full of content - javascript

I have an array full of quotes, and on load a random quote is displayed. The problem I'm having is everything works fine when I only have 2 quotes loaded, but when I added the entire list, it no longer runs.
Here is the code that works-
<div id="quotes">Quotes</div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley</b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one. </i><br><b>Bruce Lee</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>
The above works as expected, however when I add the rest of the quotes (as seen below) The script no longers works.
<div id="quotes"></div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley/b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one. </i><br><b>Bruce Lee</b>",
"<i>Success is not final, failure is not fatal: it is the courage to continue that counts.</i><br><b>Winston
Churchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>It takes courage to grow up and become who you really are.</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and
those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b> </b>",
"<i>Things do not happen. Things are made to happen.</i><br><b>John F. Kennedy</b>",
"<i>Destiny is a name often given in retrospect to choices that had dramatic consequences.</i><br><b>J.K. Rowling</b>",
"<i>When I was 5 years old, my mother always told me that happiness was the key to life.
When I went to school, they asked me what I wanted to be when I grew up. I wrote
down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t
understand life.</i><br><b>John Lennon</b>",
"<i>Not all those who wander are lost</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>It’s not hard to make decisions once you know what your values are.</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday.
Every day is a new beginning. Stay away from what might have been and look at what can
be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>If you play by the rules long enough, then you can change the game.</i><br> <b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>

You can't have newlines in JavaScript strings. You need to change this:
"str part
the rest"
to this:
"str part\nthe rest"
or
"str part\n"
+ "the rest"
You should check the JavaScript console for errors; this can help you debug

Also, you can write multiple-lined strings like this:
var str = "beginning \
continue \
end.";
The backslash before the line break is another solution.

The line breaks inside strings caused the issue. Here is fully working code:http://jsfiddle.net/whizkid747/5tyrY/
<div id="quotes">Quotes</div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley</b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one.</i><br><b>Bruce Lee</b>",
"<i>Success is not final, failure is not fatal: it is the courage to continue that counts.</i><br><b>WinstonChurchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>It takes courage to grow up and become who you really are.</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b> </b>",
"<i>Things do not happen. Things are made to happen.</i><br><b>John F. Kennedy</b>",
"<i>Destiny is a name often given in retrospect to choices that had dramatic consequences.</i><br><b>J.K. Rowling</b>",
"<i>When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.</i><br><b>John Lennon</b>",
"<i>Not all those who wander are lost</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>It’s not hard to make decisions once you know what your values are.</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday. Every day is a new beginning. Stay away from what might have been and look at what can be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>If you play by the rules long enough, then you can change the game.</i><br> <b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>

Related

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>

My switch statement or the document.write(); isn't working and i can't fix it

Hello I want to display a specific text each day and I don't know where is the problem in the following code, I am using jQuery mobile and I thought that javascript is the one that can do this on a web page.
<div data-role="content">
<div>
<script>
var n = new Date().getDay();
var ch = new String();
switch(n)
{
case 0:
{
ch = String("\“It is not so easy to leave your comfort zone, it is a very difficult thing to do,
but it most certainly will change your future and make you a better person than you ever could imagine\”<br><br>Today\'s challenge:<br><br>
Do you live in the future?<br><br>
Become aware of moments when you are lost in thinking about the future, whether it is 10 minutes or 2 years from now.
Notice how it pulls your attention from the present moment. See the reasons why you are running from your current experience.<br>");
}
break;
case 1:
ch = String("A dream is your creative vision for your life in the future. You must break out of your current comfort zone and become comfortable with the unfamiliar and the unknown.-Denis Waitley<br><br>
Today\'s challenge(Do one of them, or more if you like so...):<br><br>
Do everyday things differently.
Take a different route to work.
Try a new restaurant without checking Yelp first. Go vegetarian for a week, or a month.
Try a new operating system. Recalibrate your reality.
Whether the change you make is large or small, make a change in the way you do things on a day-to-day basis.
Look for the perspective that comes from any change, even if it\'s negative.
Don\'t be put off if things don\'t work out the way you planned.");
break;
case 2:
ch = String("Life begins at the end of your comfort zone. -Neale Donald Walsch<br<br>
Today\'s challenge:<br><br>
");
break;
case 3:
ch = String("The comfort zone is the great enemy to creativity; moving beyond it necessitates intuition,
which in turn configures new perspectives and conquers fears.- Dan Stevens<br><br>
Today\'s challenge:<br><br>
Trust yourself and make snap decisions. We\'re contradicting ourselves, but there\'s a good reason.
Just as there are people who thrive on snap decisions, others are more comfortable weighing all of
the possible options several times, over and over again. Sometimes making a snap call is in order,
just to get things moving. Doing so can help you kickstart your personal projects and teach you to trust your judgement.
It\'ll also show you there\'s fallout to quick decisions as well as slow ones.");
break;
case 4:
ch = String("Comedians tend to find a comfort zone and stay there and do lamer versions of themselves for the rest of their career.- Chris Rock<br><br>
Today\'s challenge:<br><br>
Take your time making decisions.
Sometimes slowing down is all it takes to make you uncomfortable—especially if speed and
quick thinking are prized in your work or personal life. Slow down,
observe what\'s going on, take your time to interpret what you see, and then intervene.
Sometimes just defending your right to make an educated decision can push you out of your comfort zone.
Think, don\'t just react.");
break;
case 5:
ch = String("I think when you get people who are really talented and you take them out of their comfort zone, you get a lot more out of them.- Gore Verbinski<br><br>
Today\'s challenge:<br><br>
Do it in small steps. It takes a lot of courage to break out of your comfort zone.
You get the same benefits whether you go in with both feet as you do if you start slow, so don\'t be afraid to start slow.
If you\'re socially anxious, don\'t assume you have to muster the courage to ask your crush on a date right away,
just say hello to them and see where you can go from there. Identify your fears, and then face them step by step.");
break;
case 6:
ch = String("When you go out of your comfort zone and it works there's nothing more satisfying.- Kristen Wiig<br><br>
Today\'s challenge:<br><br>
Be aware of attachment to objects<br><br>
Notice your attachments to objects such as a cool sweater, a new gadget or any other thing that would make you feel bad if you lost it.
What is the deep reason for being attached to them? Can you find the strength to let go of the attachment and give the object away?");
break;
}
document.write("<p>" + ch.big() + "</p>");
</script>
</div>
<form>
<label for="textarea-1">Post on Facebook:</label>
<textarea cols="40" rows="8" name="textarea-1" id="textarea-1" >
</textarea>
</form>
<input type="submit" value="Post to Facebook">
</div><!-- /content -->
Javascript treats every new line as separate statement and You are using multiline string
so use \ at each end of the line in string(..) to make it one string
I have edited and added \ in this demo fiddle
There's a couple of things. Like shadow said, you need to ensure the multiline strings are dealt with properly. Also in case 0: you don't need the curly brackets around the main clause. You have them right for the other cases.
I'm going to make a suggestion that might make it a bit easier. Hold the information you want in an array in an object:
obj = {
0: [
'day one',
'this is what\'s happened',
'we\'re separating up the text so that we keep the line lengths manageable'
],
1: [
'blah blah',
'blah blah'
]
};
Then all you have to do is:
var n = new Date().getDay();
var info = obj[n].join('');
document.write("<p>" + info.big() + "</p>");

javascript random quote generator not printing

I'm trying to generate a fresh quote from a list on every refresh. For some reason, I can't get the quotes to show up within the div, and I'm not sure why.
Any help would be greatly appreciated!
<div id="quotes">
<script>
var quotes = new Array();
quotes[0] = "<i>Quote 1</i><br><b>Author</b>";
quotes[1] = "<i>Quote 2</i><br><b>Author</b>";
var random = Math.ceil (Math.random() * quotes.length) - 1;
$('quotes').set('html', quotes[random]);
</script>
</div>
I've updated my code thanks to everyones help to this-
<div id="quotes"></div>
<script>
var quotes = [
"<i>"Some people feel the rain. Others just get wet."</i><br><b>Bob Marley/b>",
"<i>“Do not pray for an easy life, pray for the strength to endure a difficult one.”</i><br><b>Bruce Lee</b>",
"<i>“Success is not final, failure is not fatal: it is the courage to continue that counts.”</i><br><b>Winston
Churchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>“It takes courage to grow up and become who you really are.”</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and
those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b></b>",
"<i>“Things do not happen. Things are made to happen.”</i><br><b>John F. Kennedy</b>",
"<i>“Destiny is a name often given in retrospect to choices that had dramatic consequences.”</i><br><b>J.K. Rowling</b>",
"<i>“When I was 5 years old, my mother always told me that happiness was the key to life.
When I went to school, they asked me what I wanted to be when I grew up. I wrote
down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t
understand life.”</i><br><b>John Lennon</b>",
"<i>“Not all those who wander are lost”</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>“It’s not hard to make decisions once you know what your values are.”</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday.
Every day is a new beginning. Stay away from what might have been and look at what can
be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>“If you play by the rules long enough, then you can change the game.”</i><br><b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>
For some reason, the div is still loading without any content thought.
It was the quotes inside of my quotes messing it up. Thank you everyone for the help!!
Removing the need for any library makes the code a lot easier to not botch.
<div id="quotes"></div>
<script>
var quotes = [
"<i>Quote 1</i><br><b>Author</b>",
"<i>Quote 2</i><br><b>Author</b>"
];
document.getElementById('quotes').innerHTML =
quotes[Math.floor(Math.random() * quotes.length)];
</script>
EDIT: Nevermind, seems like $ in MooTools should indeed return the element with the id quotes. If you wanted to do the same thing with no frameworks, you could use document.getElementById('quotes').innerHTML = quotes[random].
Your $ is trying to find an element called <quotes>, not an element with the id "quotes" (assuming that it uses CSS selectors like jQuery). Using $('#quotes') should fix it.
A few other things: You could write the array in a much more concise fashion:
quotes = [
"<i>Quote 1</i><br><b>Author</b>",
"<i>Quote 2</i><br><b>Author</b>"
];
Also, you could just use Math.floor instead of Math.ceil for your random value, then you wouldn't need the - 1 at the end.

Categories