kile
kile

Reputation: 152

Scrolling div by the #id, what am I doing wrong?

I'm programming a message board for my site. Every message gets an id by auto increment in the database. The messages on the board are under "li id=#" tags where the "li" gets the id from the database. I've tried to create scrolling function via javascript so that down and up arrows would move across whole messages.

This is what I've got so far:

down.node.onclick = function() { // down arrow

var msgs = document.getElementById("kommentit"); // the <ul> element
var a = new Array();


if (msgs.hasChildNodes()) {
    var children = msgs.childNodes;
    for (var i = 0; i < children.length; i++) {
        if (msgs.childNodes[i].tagName == "LI") {
            a.push(msgs.childNodes[i].id); // array with the id's
        }
    }

}

for (var i = 0; i < a.length; i++) { // this is what goes wrong
    parent.location.href = '#' + 'a[i + 1]';
}

So while the array gets the right values the actual function doesn't work. With this code I get .../index.php#[a + 1] as my url when I click.

If I use ''+a[i + 1]+'' the page refreshes through the whole array until it settles with #undefined.

The id's are in format "id-xx" so is that the problem? I tried splitting the id by using msgs.childNodes[i].id.split("id-") but if I do this I get ",xx" as my values in the array.

Upvotes: 0

Views: 81

Answers (3)

Fender
Fender

Reputation: 3055

try that

down.node.onclick = function() { // down arrow

var msgs = document.getElementById("kommentit"); // the <ul> element
var a = new Array();


if (msgs.hasChildNodes()) {
    var children = msgs.childNodes;
    for (var i = 0; i < children.length; i++) {
        if (msgs.childNodes[i].tagName == "LI") {
            a.push(msgs.childNodes[i].id); // array with the id's
        }
    }

}

for (var i = 0; i < a.length; i++) { // this is what goes wrong
    parent.location.href = '#' + a[i];
}

Upvotes: 1

David_001
David_001

Reputation: 5802

Why are you adding 1 to the array index?

Have you tried:

for (var i = 0; i < a.length; i++) { // this is what goes wrong
    parent.location.href = '#' + a[i];
}

But I'd probably use jquery (or similar) for something like this, as changing the url like the above adds loads of things into the user's history and breaks the back button.

Upvotes: 0

Rattlemouse
Rattlemouse

Reputation: 51

If you want scroll to next item each time you have to track down the last item you scrolled to. Not to invent the bicycle, I suggest you use some JS frameworks and plugins for scrolling. It will save you a lot of time.

Examples are:

Upvotes: 1

Related Questions