2

I am trying to implement previous next functionality in Javascript but it only gives me the next element.

I have used currentItemIndex as the reverence to start for the buttons. I am starting from 5th Item and on click of next button I am trying to get 6th, 7th 8th and so on. and vice versa for previous button.

<!DOCTYPE html>
<html>
<head>
    <title>Previous Next Functionality</title>
    <script type="text/javascript">

    var myItemObjectArray = new Array();
    var currentItemIndex = 5;

    alert("CURRENT ITEM INDEX " + currentItemIndex);
    for(i=0;i<10;i++)
        {
            var ItemCatalog = new Object();

            ItemCatalog.itemId = i;
            ItemCatalog.itemName = "a"+i;

            myItemObjectArray.push(ItemCatalog);
            /*alert("OBJECT ADDED " + myItemObjectArray.length);*/
        }


    function getPrevious(currentItemIndex, myItemObjectArray)
        {
            var localCurrentItemIndex = currentItemIndex-1;
            alert("PREVIOUS OBJECT" + myItemObjectArray[localCurrentItemIndex].itemId + " " + myItemObjectArray[localCurrentItemIndex].itemName);

            // Modify Current Item Index
            currentItemIndex--;
            alert(currentItemIndex);
        }   

    function getNext(currentItemIndex, myItemObjectArray)
        {
            var localCurrentItemIndex = currentItemIndex+1; 
            alert("NEXT OBJECT" + myItemObjectArray[localCurrentItemIndex].itemId + " " + myItemObjectArray[localCurrentItemIndex].itemName);
            // Modify Current Item Index
            currentItemIndex++;
            alert(currentItemIndex);
        }   
    </script>
</head>

<body>
    <button id="previous" onclick="getPrevious(currentItemIndex, myItemObjectArray)">Previous</button>
    <button id="next" onclick="getNext(currentItemIndex, myItemObjectArray)">Next</button>
</body>
</html>

The same element keeps getting repeated.

Ankit

3
  • 1
    What elements are you trying to move next/previous through..? Commented Jan 8, 2013 at 13:31
  • I am pushing Objects in my array and am trying to iterate through each object on click of previous and next buttons Commented Jan 8, 2013 at 13:33
  • Another thing you'll need to watch out for is the currentItemIndex becoming too low/high for the length of the array (i.e. <0 or >=myItemObjectArray.length) Commented Jan 8, 2013 at 13:55

6 Answers 6

4

The problem is that your getNext and getPrevious functions have a parameter named currentItemIndex, matching the global variable you are trying to use as your maintained index counter. It's an integer, so it's passed by value, not by reference.

Because of this, when you do currentItemIndex++ or currentItemIndex--, you are changing the value of the parameter variable, NOT the global variable.

Change the name of the global variable and the corresponding increment/decrement lines at the end of the functions to match, or the name of the parameter in those two functions and the first line to match.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup. I was modifying a parameter variable. hence I was getting the same item again and again right?
2

The currentItemIndex in functions getPrevious()/getNext() is passed-by-value not by-variable/by-reference. The modifications to currentItemIndex within these functions do not propagate back to the actual parameter that you pass when the function exits.

Typical alternatives involve either:

  • using the function return to pass back the next or prev index value together with an assignment in the code that calls these functions; OR
  • creating an object that incorporates the list and a cursor, that records the position of the cursor in its state, which can be modified by methods for prev()/next()

1 Comment

Oh, I got it. I was modifying the local parameter variable right?
2

My version DEMO

Removed onclicks and put them in the head

Change show to do whatever it is you need the function to do

HTML

<button id="previous">Previous</button>
<span id="curidx"></span>
<button id="next">Next</button>

JavaScript

function show() { 
  var item = myItemObjectArray[currentItemIndex];
  document.getElementById("curidx").innerHTML=item.itemId+":"+item.itemName
  document.getElementById("previous").disabled=currentItemIndex<=0;
  document.getElementById("next").disabled=currentItemIndex>=myItemObjectArray.length-1;

}

var myItemObjectArray = new Array();
var currentItemIndex = 5;
window.onload=function() {
  document.getElementById("previous").onclick=function() {
    currentItemIndex--;
    if (currentItemIndex<=0) {
      currentItemIndex=0;
    }
    show();       
  }
  document.getElementById("next").onclick=function() {
    currentItemIndex++;
    if (currentItemIndex>=myItemObjectArray.length-1) {
      currentItemIndex=myItemObjectArray.length-1;
    }
    show();       
  }
  for(i=0;i<10;i++) {
    var ItemCatalog = new Object();
    ItemCatalog.itemId = i;
    ItemCatalog.itemName = "a"+i;
    myItemObjectArray.push(ItemCatalog);
  }
  show();
}

4 Comments

Not sure why you're using an element with id="curidx" to store the value of the current index, it's not necessary.
For debug/visualisation reasons
@mplungjan I have many html files in a folder. Is it possible to connect them so that the js gets access to the following file? So if someone is at 1.html and clicks at a next button can access to 2.html. Is it viable?
Sure, just load the page in show using some kind of Ajax
1
function getNext(currentItemIndex, myItemObjectArray)

with that function declaration you have a local (parameter) variable currentItemIndex. With the line

currentItemIndex++;

you now only modify that local variable, not the global value. Just omit it and it will work.

Or use this:

var myItemObjectArray = [];
for (i=0;i<10;i++)
    myItemObjectArray.push( {itemId: i, itemName:"a"+i} );
var currentItemIndex = 5;

function getPrevious() {
    currentItemIndex--; // the global variable
    show(currentItemIndex, myItemObjectArray);
}
function getNext() {
    currentItemIndex++; // the global variable
    show(currentItemIndex, myItemObjectArray);
}

function show(index, arr) {
    alert( arr[index].itemId + " " + arr[index].itemName);
}
<button id="previous" onclick="getPrevious()">Previous</button>
<button id="next" onclick="getNext()">Next</button>

Comments

0

Follow this code

changes made 1) onclick="getPrevious()" onclick="getNext()" no need to pass args since they are declared as global. 2) use currentItemIndex++; and currentItemIndex--; directly at the starting of the function. as seen below.

<!DOCTYPE html>
<html>
<head>
    <title>Previous Next Functionality</title>
    <script type="text/javascript">

    var myItemObjectArray = new Array();
    var currentItemIndex = 5;

    alert("CURRENT ITEM INDEX " + currentItemIndex);
    for(i=0;i<10;i++)
        {
            var ItemCatalog = new Object();

            ItemCatalog.itemId = i;
            ItemCatalog.itemName = "a"+i;

            myItemObjectArray.push(ItemCatalog);
            /*alert("OBJECT ADDED " + myItemObjectArray.length);*/
        }


    function getPrevious()
        {
            currentItemIndex--;
            alert(currentItemIndex);
            alert("PREVIOUS OBJECT" + myItemObjectArray[currentItemIndex].itemId + " " + myItemObjectArray[currentItemIndex].itemName);

            // Modify Current Item Index
        }   

    function getNext()
        {
            currentItemIndex++;
            alert(currentItemIndex);
            alert("NEXT OBJECT" + myItemObjectArray[currentItemIndex].itemId + " " + myItemObjectArray[currentItemIndex].itemName);
            // Modify Current Item Index

        }   
    </script>
</head>

<body>
<button id="previous" onclick="getPrevious()">Previous</button>
<button id="next" onclick="getNext()">Next</button>
</body>
</html>

3 Comments

That will work, but it eliminates the possibility of reusing getPrevious/getNext for iterating through some other array in future.
I don't think so because prev and next fun are like push and pop which are predefined.
push and pop are functions that exist on the Array prototype, and I can see why you might want to have getNext/getPrevious functions callable in the same way (and have the currentIndex inherent to the array - see @Paul's edited answer), but to me it didn't look like what the OP was trying to achieve. To set that up properly would be more complex than this question.
0
var myItemObjectArray = new Array();
var currentItemIndex = 5;

alert("CURRENT ITEM INDEX " + currentItemIndex);
for(i=0;i<10;i++)
    {
        var ItemCatalog = new Object();

        ItemCatalog.itemId = i;
        ItemCatalog.itemName = "a"+i;

        myItemObjectArray.push(ItemCatalog);
        /*alert("OBJECT ADDED " + myItemObjectArray.length);*/
    }

function getPrevious(currentItemIndex, myItemObjectArray)
    {
        if(currentItemIndex > myItemObjectArray.length)
                {
                    alert("THERE ARE NO MORE ITEMS TO DISPLAY");
                }
        var localCurrentItemIndex = currentItemIndex-1;
        alert("PREVIOUS OBJECT" + myItemObjectArray[localCurrentItemIndex].itemId + " " + myItemObjectArray[localCurrentItemIndex].itemName);

        // Modify Current Item Index
        modifyCurrentIndex("previous");
    }   

function getNext(currentItemIndex, myItemObjectArray)
    {
        var localCurrentItemIndex = currentItemIndex+1; 
        alert("NEXT OBJECT" + myItemObjectArray[localCurrentItemIndex].itemId + " " + myItemObjectArray[localCurrentItemIndex].itemName);
        // Modify Current Item Index
        modifyCurrentIndex("next");
    }   

    function modifyCurrentIndex(mode)
        {
            if(mode == "next")
                {
                    currentItemIndex = currentItemIndex + 1;
                } else if(mode == "previous")
                    {
                        currentItemIndex = currentItemIndex - 1;
                    }
        }

I used a separate function to modify the global variables. I got the idea from the above solutions too.

Thanks, Ankit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.