0

I have an array set up that changes the h1 on my site when the user clicks a button. However, on initial page load, the h1 shows up empty. The heading will not actually display until the button is clicked. Was wondering if anyone knew of a quick fix to set the default value of this array so it is not empty when page is first loaded (I realize I could just put text in the h1 in the HTML, but would rather have everything pulled form this array):

  var arr = ["Whiskey","Vodka","Rum","Tequila"];
  var index = 0;

  $('.button').click(function(){
    $('h1#heading').html(arr[index]);
    index = (index + 1) % arr.length ;
 });

2 Answers 2

0

Your array is just fine, what lacks a default value is the h1. You can initialize it after the document loads with the following code:

$(document).ready(function() {
  $('h1#heading').html(arr[0]);
});
0

You could trigger the click event right after binding it.

  $('.button').click(function(){
    $('h1#heading').html(arr[index]);
    index = (index + 1) % arr.length ;
  }).click();

or use .trigger('click');

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.