Reputation: 31
I am trying to change the value of x, using the changePost function.
When the changePost function is fired it should change the value of x to the corresponding posts[i].
var x = 0; var title = posts[x].title, date = posts[x].date, content = posts[x].content, author = posts[x].author;
<article>
<h2>$title</h2>
<small>$date.format()</small>
<p>$content</p>
<cite>$author</cite>
</article>
for(var i in posts) { var title = posts[i].title, date = posts[i].date, content = posts[i].content, author = posts[i].author;
<article>
<h3 onclick="changePost()">$title</h3>
<small>$date.format()</small>
</article>
}
</aside>
function changePost(){ var x = i; };
Thanks.
Upvotes: 0
Views: 90
Reputation: 327
I understand you want to browse an array of posts by clicking a next button. I would advise you to separate your post template, your post-browse functionality and the events that must trigger the change of post content.
For creating a template you could use Underscore's template function. Or EJS. And probably many other template libraries.
For manipulating the dom I would advise jQuery but you could do without.
Make sure all HTML is loaded before you try access elements in the page.
Visit this JS Fiddle
The markup:
<div id="post"></div>
<a href="#" id="next">next</a>
The code:
// A simple wrapper for your posts so your index variable cant be overwritten
// by some other peace of code
var posts = (function() {
// The template for the posts, using Underscore's template function
var tpl = _.template("<h2><%= title %></h2><p><%= content %></p>");
// The index of the current post
var index = 0;
// The array of posts
var posts = [
{title:"Title 1", content:'Bla bla lorem'},
{title:"Title 2", content:'Bla bla ipsum'},
{title:"Title 3", content:'Bla bla dolor'},
{title:"Title 4", content:'Bla bla sit'},
{title:"Title 5", content:'Bla bla amet'}
];
// The functions available to the document
return {
next:function(){
if(++index >= posts.length) {
index = 0;
}
return tpl(posts[index]);
},
load:function(){
return tpl(posts[index]);
}
}
}());
// Use of your posts object by the html document
document.getElementById('post').innerHTML = posts.load();
document.getElementById('next').onclick = function(){
document.getElementById('post').innerHTML = posts.next();
}
Upvotes: 0
Reputation: 3989
Your problem is not just changing the x
value, you have to re-render the template every time you change the x
.
var main_template = document.getElementById('mainTemplate').innerHTML;
function changePost(x) {
main.post_id = x;
document.getElementById('main').innerHTML = T(main_template, main);
}
Here's the fiddle: http://jsfiddle.net/bcq7580s/5/
Alternative would be to render all the post, hide them all via css, and then when the user clicks the link, hide all visible posts, and then show just the one the user picked.
Upvotes: 1