Nasłuchiwacze w JavaScript (addEventListener)

Wywołanie funkcji po przeskrolowaniu do obiektu o danym id

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="main_title">Main title</div>
    <p>This is an intro</p>
    <button>Click me</button>
    <p id="intro">This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <div id="a">a</div>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <div id="b">b</div>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <p>This is an article</p>    <p>This is an article</p>    <p>This is an article</p>
    <script type="text/javascript" src="main.js"></script>
</body>
</html>
window.addEventListener("scroll", doOnScroll);
const targetEl = document.getElementById("a");
function doOnScroll(){
    if(targetEl && window.scrollY > targetEl.offsetTop - 200){
        window.alert("Hello!");
        window.removeEventListener("scroll", doOnScroll);
    }
}

Dodanie Listenera po załadowaniu DOMu

<!DOCTYPE html>
<html lang="pl">
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<script>
    function init(){
        document.getElementById("panel").textContent = "DOM Załadowany";
    }
    document.addEventListener("DOMContentLoaded",init,false);
</script>
<body>
    <div id="panel">OK</div>
</body>    
</html>
Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Scroll to Top