Vignesh Chinnaiyan Vignesh Chinnaiyan - 5 months ago 13
Javascript Question

Javascript pass variable value from one function to another

I need to pass the value 7 as a parameter whenever i call

check_scroll()
function.

But now the
lastcount
value keeps on increasing even though i call
check_scroll()
function.

Please keep me some suggestion.

Check the code snippet as like i say,

first click on the
first click me to initiate check_scroll function
button, then scroll inside the
div
, you get an alert with value incrementing by 7.

Then click the button and then again scroll, but now the alert wont start from 7.



$("#mybutton").click(function() {

check_scroll(7);

})

function check_scroll(val) {

var lastcount = val;
$('#notification_ul').scroll(function() {
if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) {

$("#notification_ul").append("<br/> Some Text Append <br/>");
alert(lastcount);

lastcount = lastcount + 7;
}

})
}

div {
width: 200px;
height: 200px;
overflow: auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification_ul">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

<button id="mybutton">
first click me to initiate check_scroll function
</button>




Answer
  • define scroll event only once,
  • move lastcount to outside
  • when button is clicked, reset the last count
$(function(){
    var lastcount = 0;

    $("#mybutton").click(function() {
        check_scroll(7);
    });

    $('#notification_ul').scroll(function() {
        if (lastcount !== 0) {
            if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) {
                $("#notification_ul").append("<br/> Some Text Append <br/>");
                console.log(lastcount);
                lastcount = lastcount + 7;
            }
        }
    });
});

function check_scroll(val) {
    lastcount = val;
}