Paul Paul - 1 month ago 11
jQuery Question

JavaScript erratic with starting point funciton

fairly new to js. I have a simple project in which all I have is an image twice the height of the screen. I want the webpage to open at the bottom of the page, so I have added the "window.scroll" funtion method in javascript. This works fine... most of the time. Sometimes, particularly if I test on a mobile device with a home server, the javascript just doesn't fire up and the page starts at the top. So my main question is: is there a way to do the same as "window.scroll" but with CSS, bypassing js altogether? And a second question I would have is, why is javascript so flaky? I am really new to web development and I have already twice (the other time with the "slide" method) had to use css instead of js because js doesn't work properly, or it needs to be cached etc... is this normal behaivour or just me really bad at writing it at this point? Thanks for your time. P

Here's the simple code:



$(document).ready(function(){

window.scroll(0,2000);

});

body {
margin: 0px;
padding: 0px;
}

img {
width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>

</head>
<body>
<img src="https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455_960_720.jpg" width="100%" style="display: block;">
</body>
</html>





CSS:

body {
margin: 0px;
padding: 0px;
}

img {
width: 100%;
}


JavaScript:

$(document).ready(function(){

window.scroll(0,2000);

});

O_Z O_Z
Answer

I think the problem is that the image takes time to load.So I think your event is fired however the image loads later and changes the page size again. The load event will fire after images are loaded.

try this code instead:

$(window).on("load", ,function(){

    window.scroll(0,2000);

});