0

I am trying to get a simple text change on refresh:

<strong>Title</strong>
<p id="myQuote">Slogan</p>

And the "Slogan" part changes on refresh:

var myQuotes = new Array();
myQuotes[0] = "To be or not to be";
myQuotes[1] = "The only thing we have to fear is fear itself";
myQuotes[2] = "Give me liberty or give me death";

var myRandom = Math.floor(Math.random()*myQuotes.length);

$('#myQuote').html(myQuotes[myRandom]);
ryantpayton
  • 385
  • 4
  • 18

3 Answers3

1

You can't select or manipulate DOM elements until the DOM is loaded.

Wrap your $('#myQuote').html call inside a $(document).ready(function() { ... }), as demonstated in this fiddle.

Alternatively, put your <script> tag at the bottom of your <body> so it loads after the rest of the DOM. (See further discussion of your load-time options in Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?.)

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 1
    Actually you can: http://jsfiddle.net/Hn6fL/2/ you just need to run the code after the specific elements you're targeting are loaded. – Christophe Dec 10 '12 at 18:39
  • Did you edit my fiddle or make your own with my code? The load-time drop down must be set to `no wrap (head)` or else it gets wrapped anyway by jsfiddle. Here is a non-working fiddle: http://jsfiddle.net/T3htp/ – apsillers Dec 10 '12 at 18:40
  • Are you saying that the code gets wrapped even if you select no wrap (body)? – Christophe Dec 10 '12 at 18:44
  • Nope! In that case it gets placed at the bottom of the ``, as you suggested in your alternative (which I've added to my answer). I only said "or else it gets wrapped" since that's the jsfiddle default; the no-wrap-body option also does not wrap (as the name suggests). – apsillers Dec 10 '12 at 19:18
0

My guess is jQuery is not loaded....

if (jQuery) {  
    alert('jQuery is loaded'); 
} else {
    alert('not loaded');
}

Then check if you are getting a value from the random function.

var myRandom = Math.floor(Math.random()*myQuotes.length);

alert(myQuotes[myRandom]); //Add this to your code

$('#myQuote').html(myQuotes[myRandom]);
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
0

Replace the following to avoid using jQuery in your script

http://jsfiddle.net/TYEGh/

$('#myQuote').html(myQuotes[myRandom]);

with

document.getElementById('myQuote').innerHTML= myQuotes[myRandom];
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124