Anjali
Anjali

Reputation: 2698

executing jquery script only once first time when page loads

I have the following jquery script on my web page. This script is ran when I load the page the very first time. I don't want this script to run again, only the first time when the page loads. Is it possible to do that? I googled it and someone mentioned that I can put .one and then it will be executed only once. Below is the code:

 $(document).ready(function () {
        //Scroll div you the bottom onpage load
        $("#divTest").scrollTop($("#divTest")[0].scrollHeight);
    });

My issue is I have a datagrid on this page that is inside the div tags. When I update the datagrid. The scroll bar of the datagrid goes all the way to the bottom. Although, I want, when I do the update on the datagrid, the row that has been updated the page should stay there. For this purpose, I have the following code on the page. User wants that when they are first redirected to this page that has datagrid on it, the scroll bar should be all the way to the bottom and that is the reason, I have above jquery in it.

<div id="divTest" style="overflow:auto; height:900px; width:1600px" onscroll="SetDivPosition()" >

The javascript is like this

       function SetDivPosition() {
        var intY = document.getElementById("divTest").scrollTop;
        document.cookie = "yPos=!~" + intY + "~!";
    }

and this

     window.onload = function () {
        var strCook = document.cookie;
        if (strCook.indexOf("!~") != 0) {
            var intS = strCook.indexOf("!~");
            var intE = strCook.indexOf("~!");
            var strPos = strCook.substring(intS + 2, intE);
            document.getElementById("divTest").scrollTop = strPos;
        }
    }

Upvotes: 1

Views: 4446

Answers (2)

ameenulla0007
ameenulla0007

Reputation: 2683

$(document).ready(function () {
if($.cookie("scriptExecuted")!="yes") {
        //Scroll div you the bottom onpage load
        $("#divTest").scrollTop($("#divTest")[0].scrollHeight);
        $.cookie("scriptExecuted", "yes");
}
});

Use of cookies would be helpful, you can use this lovely jquery plugin to set, unset and retrieve cookie values. https://github.com/carhartl/jquery-cookie

Logic is simple, check for the set cookie, if not set execute, and when executed, set the cookie.

CDN for jQuery-Cookies https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js

here goes the working fiddle : https://jsfiddle.net/kzLkg1rk/

Upvotes: 1

H.B
H.B

Reputation: 107

When you say once do you mean once per page load or once in all?

If it is once per page load then I am positive that your code will work. If no event is called then this should happen only once.If it keeps happening check how many times you are loading the script.

If you mean you don't want it to run anymore but the one time a browser loads it then you need a cookie.

Upvotes: 0

Related Questions