0

I try to get the values form Button elements:

<script>
    var elmnt = document.getElementById('<%= Button1.ClientID %>');
    var elmnt2 = document.getElementById('<%= Button2.ClientID %>');
    var x = elmnt.scrollLeft;
    var y = elmnt.scrollTop;
    var x2 = elmnt2.scrollLeft;
    var y2 = elmnt2.scrollTop;
    function ToTopOfPage(sender, args) { setTimeout("window.scrollTo(x, y)", 0); }
    function ToTopOfPage2(sender, args) { setTimeout("window.scrollTo(x2, y2)", 0); }

</script>      

When I click on the Button1 or Button2 does not jump to the element Here is the Button codes:

Button1:

 ScriptManager.RegisterStartupScript(this, Page.GetType(), "ToTheTop", "ToTopOfPage();", true); 

Button2:

 ScriptManager.RegisterStartupScript(this, Page.GetType(), "ToTheTop", "ToTopOfPage2();", true);

When I add some values to scrollTo() method for example window.scrollTo(2000,1000) the method works fine but when I assign a dinamic value does not work window.scrollTo(x,y).

DemGergo
  • 21
  • 2

1 Answers1

0

setTimeout takes a function as its first parameter, and variables as the 3rd/4th/... parameter. Apparently it can convert a string containing function and parameters, but you really should forget that, and do something like:

function ToTopOfPage(sender, x, y) {
    setTimeout(window.scrollTo, 0, x, y); 
}

EDIT: I find it hard to believe that it works with hardcoded values and the whole lot as a string, but not when it's done with variables. You may want to recheck your variables:

function testScrollTo(x,y) {
    console.log("x: ", x);
    console.log("y: ", y);
    window.scrollTo(x,y);
}

function ToTopOfPage(sender, x, y) {
    setTimeout(testScrollTo, 0, x, y); 
}
yezzz
  • 2,990
  • 1
  • 10
  • 19
  • This doesn`t work for me just when instead of x, y I give a fix value. – DemGergo Oct 25 '18 at 22:10
  • Are you saying my answer doesn`t work for you, and only a fixed value works? – yezzz Oct 25 '18 at 22:25
  • Yes, for example setTimeout(window.scrollTo, 0, 2000,1000); this brings the button to a position but when I assign the variables setTimeout(window.scrollTo, 0,x,y); nothing happening. – DemGergo Oct 25 '18 at 22:42
  • I think you should console.log your variables to check them. Also be aware that you only pass a reference, ie. the value itself may change... eg. see https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values – yezzz Oct 25 '18 at 22:59
  • There is no problem with setTimeout, the problem is with the scrollTo() method somehow does not recognize assigned variables just numbers. – DemGergo Oct 25 '18 at 23:11