0

If I add this piece of code to a simple HTML page created in Visual Studio then it works. (I get values greater than 0 for windowLeft and windowTop.

$(document).ready(function() {
    $(document).click(function(e) {
        var windowLeft = $(window).scrollLeft();
        var windowTop = $(window).scrollTop();

        var message = "Window Left: " + windowLeft + "\n" +
                      "Window Top: " + windowTop;
        alert(message);
    });
});

If I add the exact code to a Script Editor Web Part on a web part page in SharePoint 2013, then scrollLeft() and scrollTop() always returns 0 even when I scrolled all the way to the right and bottom of the page.

Tried in IE11 and Chrome, and the same jQuery library is referenced by both environments. I've tested over a few hours but still can figure out why...

I hope someone can help me solve this puzzle. Thank you.

1 Answer 1

1

SharePoint team embedded many JavaScript files in masterpage and they do many thing after $(document).ready(). You code is overridden by these JavaScript file by Microsoft. There are some options available to hook custom code after PageLoad.

  • SP.SOD.execute
  • SP.SOD.executeFunc
  • ExecuteOrDelayUntilScriptLoaded
  • SP.SOD.executeOrDelayUntilScriptLoaded
  • LoadSodByKey

Execute after specific JavaScript file, Check this

SP.SOD.executeFunc("SP.js", "SP.core.js", function() { function init() { //your code goes here... } init(); });

Load on the end. function runAtTheEnd(){ // your code } _spBodyOnLoadFunctionNames.push("runAtTheEnd");

Delay until load
function runAfterSpJs(){ //your code } ExecuteOrDelayUntilScriptLoaded(runAfterSpJs, "sp.js")

1
  • Thanks Asim. I'll try the SP.SOD methods. I've seen the use of these methods before, and even I used some of them myself, but I've not understand them 100% due to lack of documentation. For example: SP.SOD.executeFunc(key, functionName, fn), where the second argument should be a function name, but in your example it looks like a file name instead, and I think your example is correct.
    – Conax
    Jan 11, 2017 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.