Reputation: 749
I have a large canvas with an interactive Processing sketch that i want to run as soon as the page is loaded. For some reason when the user clicks on the screen (on the canvas) for the first time, the page scrolls down a tiny bit. It is annoying because the user misses the click target when interacting with the sketch for the first time (wait until text "click on any species" appears).
http://417i.com/alcazar-vegetal/
I have tried focusing the canvas element on page load, also clicking via javascript, and even preventDefault, but nothing worked.
<!DOCTYPE html>
<html>
<head>
<meta name="Alcazar Vegetal" CONTENT="Alcazar Vegetal">
<title>Alcazar Vegetal</title>
<script src="processing-1.4.1.min.js"></script>
<script>
document.onload = function() {
var elem = document.getElementById("main_canvas");
elem.click();
elem.focus();
elem.preventDefault();
}
</script>
<style>
canvas{border:0px;margin:0px;padding:0px;outline:none;}
canvas:focus{outline:none;}
</style>
</head>
<body bgcolor="white" style="color:rgb(20,20,20)">
<canvas datasrc="alcazar_vegetal_viz_Pjs.pde" tabindex="1"></canvas>
<br>
<br>
</body>
</html>
Upvotes: 0
Views: 1381
Reputation: 42174
This is the correct default behavior of the browser. It has nothing to do with P5.js or even JavaScript.
Think about it this way: let's say you have a page full of buttons, and those buttons go past the bottom of the viewport. Now a user (who can't use a mouse due to accessibility issues) interacts with the page using the tab
key. Pressing the tab
key changes the focus. The user keeps pressing the tab key until the focus goes to a button that's below the viewport. That causes the viewport to scroll so the button is in view.
That's what's happening here. Clicking on the canvas causes it to gain the focus, and gaining the focus causes the viewport to scroll so the canvas is fully visible.
To get around this, there are a few things you can do:
preventScroll
parameter on this page seems promising. See also: Preventing page from scrolling on focus switching and disable scrolling on input focus in javascript, If I were you I'd go with the third option, but it's really up to you. If you still can't get it working, please post a MCVE in a new question post and we'll go from there. Good luck.
Upvotes: 1