Skip to content Skip to sidebar Skip to footer

Getting Next And Previous Element Of Json Array

I need help with my code. I want to have a previous and a next button, these will call a function viewBlogItem(direction,cat,blogid); in that function i'll be reading out the json

Solution 1:

How can I tell that there ain't another blog after or previous?

Look at the index of the current blog item and see if the next one is bigger than than the number of items in the array or if the previous one is less than 0.

var blogs = {
    "blogItem": [{
        "id": 1,
        "title": "animals blog 1",
        "category": "animals",
        "text": "text",
        "articleid": 1
    }, {
        "id": 2,
        "title": "lifestyle blog 1",
        "category": "lifestyle",
        "text": "text",
        "articleid": 1
    }, {
        "id": 3,
        "title": "animals blog 2",
        "category": "animals",
        "text": "text",
        "articleid": 2
    }, {
        "id": 5,
        "title": "animals blog 4",
        "category": "dieren",
        "text": "text",
        "articleid": 4
    }, {
        "id": 4,
        "title": "animals blog 5",
        "category": "animals",
        "text": "text",
        "articleid": 3
    }]
};

var index = 0;
var item = blogs.blogItem[index];

var title = document.getElementById('title');
var text = document.getElementById('text');
var previous = document.getElementById('previous');
var next = document.getElementById('next');

displayItem(item);

previous.addEventListener('click', function() {
    displayItem(blogs.blogItem[--index]);
});

next.addEventListener('click', function() {
    displayItem(blogs.blogItem[++index]);
});

functiondisplayItem(item) {
    title.innerText = item.title;
    text.innerText = item.text;
    previous.disabled = index <= 0;
    next.disabled = index >= blogs.blogItem.length -1;
}
[disabled] {
    opacity: 0.5;
}
<linkhref="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"rel="stylesheet"/><divclass="container"><div><divid="title"></div><divid="text"></div></div><buttonid="previous">Previous</button><buttonid="next">Next</button></div>

Post a Comment for "Getting Next And Previous Element Of Json Array"