DCJones
DCJones

Reputation: 3461

Running an if statement if counter > 5

I have a script that produces a table of data dynamically depending on the number of records returns by a query.

What I am trying to do is run part two of my jquery script if the rows in the table are greater than 5.

My script:

        Counter = 0;
        $(document).ready(function() {

            function get_data() {
                    $.getJSON("get_data_logos.php", function(json){
                    json = json[0].data;
                    var tr ;
                    $('table').html("");

                    for (var i = 0; i < json.length; i++) {
                        tr = $('<tr/>');
                        tr.css("border-bottom","2px solid #FFF");
                tr.append("<td width='15%'><div class='clientimage'><img src='../../../../conf_images/boards/" + json[i].ClientImageName + "'></></div></td>");
                tr.append("<td width='33%'><div class='clientname-text'>" + json[i].ClientName + "</div></td>");
                tr.append("<td width='33%'><div class='roomname-text'>" + json[i].RoomName + "</div></td>");
                tr.append("<td width='33%'><div class='time-text'>" + json[i].RoomFromTime + " - " + json[i].RoomToTime + "</div></td>");
                Counter++;
                console.log(Counter)
                $('table').append(tr);
                    }
                });
        }
        get_data();
        setInterval(get_data,60000)
        });

        //PART TWO

        if(Counter > 5) {
            var my_time;
            $(document).ready(function() {
            pageScroll();
            });

            function pageScroll() {
            var objDiv = document.getElementById("contain");
            objDiv.scrollTop = objDiv.scrollTop + 1;
            console.log(objDiv);

            if (objDiv.scrollTop == (objDiv.scrollHeight - 550)) {
            objDiv.scrollTop = 0;
            }
            my_time = setTimeout('pageScroll()', 50);
            }
        }

Many thanks in advance for your time.

Upvotes: 0

Views: 148

Answers (1)

James Douglas
James Douglas

Reputation: 3446

The problem is that the if statement only fires once - when the page loads. I would syggest putting the it into a function, and calling that function every time the for loop goes around.

Counter = 0;
for (i=1; i<=10; i++) {
  Counter++;
  console.log('This is test number ' + Counter);
  test();
}
function test() {
  if (Counter > 5) {
    console.log('Counter is higher than 5!');
  }
}

That activates the function every time the Counter is higher than 5. If you want it to activate only the first time it exceeds 5, then just check if the value is six.

Counter = 0;
for (i=1; i<=10; i++) {
  Counter++;
  console.log('This is test number ' + Counter);
  test();
}
function test() {
  if (Counter == 6) {
    console.log('Counter has reached the value 6!');
  }
}

Upvotes: 1

Related Questions