user2265229
user2265229

Reputation: 151

How to execute js(scrollLeft) from php?

i have a function to scroll a div like this:

function scrTo(id, to)
{
    document.getElementById(id).scrollLeft = to;
}

and try to call it via php:

echo"<div id='movingtab' style='overflow-x:auto; width:765;'>";
echo"<table>...Some Table Content...</table>";
echo"</div>";
if(isset($_GET['scrl']))
{
    echo"<script type='text/javascript'>";
    echo"scrTo('movingtab', '".$_GET['scrl']."');";
    echo"</script>";
}

The idea is to scroll to last position after the content of div changed via ajax, but when the script executed the scroll is back to begining and not back to last scroll position before div content loaded. I've try to call the function via <script onload="">, but still not working. Can anyone help solve my problem?

Upvotes: 0

Views: 118

Answers (3)

Maarten Venema
Maarten Venema

Reputation: 324

Your approach is wrong. You should call the function in the callback of your ajax request. This functionality should be done solely in JavaScript. If you are echoing JavaScript from PHP it is most probably the wrong approach.

Upvotes: 1

Mike Wells
Mike Wells

Reputation: 425

<?php if(isset($_GET['scrl'])) { ?>
    <script type='text/javascript'>
        function scrTo(id, to){
            document.getElementById(id).scrollLeft = to;
        }
    </script>
<?php } ?>
<div id='movingtab' style='overflow:auto; width:765px; border:1px solid blue;'>
    <table><tr><td>...Some Table Content...</td></tr></table>
</div>
<button id="scroll" onclick="scrTo('movingtab', '<?php echo $_GET['scrl']; ?>')">scrollLeft()</button>

Upvotes: 1

Edan Feiles
Edan Feiles

Reputation: 465

Probably Should use:

echo "<script type='text/javascript'>
$(document).ready(function() {
     scrTo('movingtab', '".$_GET['scrl']."');
});
</script>";

Upvotes: 1

Related Questions