user1412
user1412

Reputation: 23

Incrementing Variable Function Not Working

I'm building something from scratch though I'm new to JavaScript. Right now, all I want is for a variable - currBook - to increment by one when a button is pressed. That variable controls what's being pulled from an Array - bookTitlesList. I can get the titles to show now, but the variable won't increment. The function that's supposed to increment it, advanceBooks, is working because I used an alert to make sure. Any help would be appreciated! Below is the code.

My JavaScript

<script>
var bookTitlesList = ["To Kill A Mockingbird", "The Lord of the Rings", "A Tale of Two Cities"]; 
var currBook = 0; 
var bookTitle = document.getElementById("bookTitle"); 
var nextBook = document.getElementById("nextBook");

function loadTitle() { 
    bookTitle.innerHTML = bookTitlesList[currBook]; 
    nextBook.innerHTML = bookTitlesList[currBook+1]; 
};

function advanceBook() { 
    alert("This works!"); 
    currBook++; 
}; 
console.log(advanceBook);
</script>

My HTML

<html>
<body onload="loadTitle()">
    <h1>Top 100 Best Selling Books</h1>
    <h2 id="bookTitle">Book Titles Go Here</h2>
    <button onclick="advanceBook()" id="nextBook">The Next Book Title Goes Here</button>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

Upvotes: 2

Views: 86

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173572

When you call advanceBook() you need to call loadTitle() again (it's like refreshing your view).

Additionally, you will want to make sure that you don't bust your bookTitlesList array; for example, you could make it wrap, so after the last book you get the first one again:

// get next book index and wrap when reaching the end
function nextBookIndex(bookIndex)
{
    return (currBook + 1) % bookTitlesList.length;;
}

function advanceBook() { 
    currBook = nextBookIndex(currBook);
    loadTitle(); // update page
}; 

function loadTitle() { 
    bookTitle.innerHTML = bookTitlesList[currBook]; 
    nextBook.innerHTML = bookTitlesList[nextBookIndex(currBook)];
};

Upvotes: 1

plalx
plalx

Reputation: 43718

When you advance, you should also call loadTitle() to update the book title in the DOM.

function advanceBook() { 
    alert("This works!");
    currBook++;
    loadTitle();
};

Upvotes: 2

Jeff Bowman
Jeff Bowman

Reputation: 95654

console.log(advanceBook);

Be aware that this does not call advanceBook, but just refers to it as a variable that happens to hold a function. To call advanceBook, even though it doesn't return anything, use this:

console.log(advanceBook());

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You are indeed calling advanceBook(), but at no point are you calling loadTitle(), which is required to display the next book's title in your page.

Upvotes: 2

Related Questions