Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Pagination Prototype JavaScript - Quiz Example

Hello Everyone, Hello Team Tree House,

I have written the following code thanks to some code I found on Treehouse's forum. However, i am facing a difficulty of pagination, and i think it is because JavaScript file read getElementByClassName before it has been created.

I have an alert that is not trigger when clicking

Hence, I am wondering how should I proceed. Here is my code:

https://w.trhou.se/hycs0lrpdd

Enjoy ;) Thanks in advance,

2 Answers

Steven Parker
Steven Parker
243,318 Points

You seem to have partly answered your own question.

You're correct — you cannot attach a click handler to an element that has not been created yet. Also, remember that getElementsByClassName returns a collection of elements, so you'll need to apply indexing to it when you do attach the handler.

Your next step should probably be to redesign the sequence of events so that the elements(s) get created before the handlers are attached. Alternatively, if you use a plug-in like jQuery or FT DOM Delegate you can set up a delegated event handler that will be effective on elements that are created after it is established.

Yes exactly, this is what i did:

var questionsMobilite = [ new Question ( "mobilite", '1', "Vous habitez dans: ", ["après 1980", "Mitoyenne après 1980"] ), new Question ( 'mobilite', '2', 'Vous habitez dans: ', ['après 1980', 'Mitoyenne après 1980'] ) ];

var quizMobilite = new Quiz(questionsMobilite, 'mobilite');

var lengthPaginationMobilite = questionsMobilite.length;

for (i = 0; i < lengthPaginationMobilite; i++){ var div = document.createElement("button");
div.id = (i+1); div.className = 'pagination'; content = document.createTextNode(i+1); div.appendChild(content);

document.getElementById('progress').appendChild(div);

}

quizMobilite.runQuizUI();

And it works perfectly, thanks for the advice, especially the indexing.