I am working on a small HTML/JavaScript application where a user can browse through different content without refreshing the page. I use divs as 'pages' by showing and hiding the divs as the user navigates through the application. Between two pages occurs a small animation (like fading or sliding). When the animation is finished and the 'page' is visible a trigger is fired.
Each page executes his own behavior when triggered (e.g. playing a video/animation/show some text). Each page(div) has his own JavaScript class linked to it. The Class name of the JavaScript class is stored in a data attribute called data-pageClass:
<div id="page1" class="pn-page intro" data-pageClass="IntroPage">
Page 1: introduction text
</div>
<div id="page2" class="pn-page page2" data-pageClass="VideoPage">
Page 2: playing a video here
</div>
The class handling the navigation creates the classes of the pages by looping through the html structure and using the data attribute to identify which class to create. I use the 'stringToFunction' function described in this question on StackOverflow
Looping code:
$("#pages .pn-page").each(function (i, el) {
var PageClass = stringToFunction(el.getAttribute("data-pageClass"));
var newPage = new PageClass(el);
_this.pages.push(newPage)
});
For simplicity's sake I left out all the other code. please let me know when it's unclear.
So my question is if it is bad practice to 'dynamically' create objects in this way. I thought it very useful to link divs to custom javascript classes (a bit like DOM does).