Javascript DOM onscroll Event

Introduction

Execute a JavaScript when a <div> element is being scrolled:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {// w w w.  jav  a2s  . co  m
  border: 1px solid black;
  width: 200px;
  height: 100px;
  overflow: scroll;
}
</style>
</head>
<body>
<p>Try the scrollbar in div.</p>

<div onscroll="myFunction()">
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
This is a test. <br><br>
</div>

<p>Scrolled <span id="demo">0</span> times.</p>

<script>
var x = 0;
function myFunction() {
  document.getElementById("demo").innerHTML = x += 1;
}
</script>

</body>
</html>

The onscroll event occurs when an element's scrollbar is being scrolled.

You can use the CSS overflow style property to create a scrollbar for an element.

Bubbles:
Cancelable:
Event type:
Supported HTML tags:

























No
No
UiEvent if generated from a user interface, Event otherwise
<address>,
<blockquote>,
<body>,
<caption>,
<center>,
<dd>,
<dir>,
<div>,
<dl>,
<dt>,
<fieldset>,
<form>,
<h1> to <h6>,
<html>,
<li>,
<menu>,
<object>,
<ol>,
<p>,
<pre>,
<select>,
<tbody>,
<textarea>,
<tfoot>,
<thead>,
<ul>



PreviousNext

Related