javascriptjqueryuser-interfacejscrollbarjquery-jscroll

using jQuery scollLeft() method to scroll to the right by default, what is wrong with my code?


Here is my code:

<head>
    <title>Labs</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var left = $('.entry-content').width();
$('.entry-content').scrollLeft(left);
</script>
</head>
<body>
    <div class="container"> 
        <div class="entry-content"><img src="map.png"></div>
    </div>
</body>

I want the scroll to display to the far right automatically when the user visits the page. Currently it scrolls to the left by default. Please tell me what's wrong with my code.


Solution

  • Make sure you include that script after the DOM element, or wrap it in a DOMContentLoaded handler. For example:

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var left = $('.entry-content').width();
            $('.entry-content').scrollLeft(left);
        });
    </script>
    

    In your example it's impossible for the selectors $('.entry-content') to select the actual element, because it does not yet exist when the javascript code runs. The DOM is parsed top to bottom, and any scripts that are found along the way are executed immediately.


    As Nelson also points out in his answer, it is also a good idea to keep in mind that the image might take a while to load. Only once it is loaded, the image will start to occupy the actual space it needs. So, if you measure the dimensions of .entry-content before the image loads, you get a number that is inaccurate if the image requires more horizontal space than the containing element naturally occupies.

    To fix this you can listen for the "load" event on window instead, which will always fire after DOMContentLoaded, and not before all resources (among which your image) have been loaded:

    <script>
        window.addEventListener('load', function() {
            var left = $('.entry-content').width();
            $('.entry-content').scrollLeft(left);
        });
    </script>
    

    This example is equivalent to Nelson's answer.