Skip to content

Run a javascript function from HTML events

I’m working on a project that animate on page scroll. This is the element I want to animate.

<h1 style="position: relative; top: 0; left: 0;"
        data-animate-left="50px" data-animate-top="50px" 
        data-animate-time="0.2s">Animation on scroll</h1>

This is my JavaScript

function animateAfterPosition(scroll) {
        if (window.scrollY <= scroll) {
        } else {

And this is my CSS

.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);}

I need to run the function animateAfterPosition from the html. I expected to run the function with onscroll event, but it doesn’t work. So how can I do this?

I found that css attr() is only working with the content: property and I managed to do it with JavaScript


You need to add selector to toggle class the animation. And your current css doesn’t have enough height to make scrolling window. Here’s an simple snippet to run your function onload, update onscroll and toggling class.

var dataAnimate = document.querySelector('[data-animate]');

function animateAfterPosition(scroll) {
  dataAnimate.classList.toggle('active', window.scrollY <= scroll);

window.addEventListener("scroll", function() {
  return animateAfterPosition(200);
.animateAfterPosition {
  transition: attr(data-animate-time);
  left: attr(data-animate-left);
  top: attr(data-animate-top);

[data-animate] {
  height: 1000px;
<body onload="animateAfterPosition(200)">
  <h1 style="position: relative; top: 0; left: 0;"data-animate-left="50px" data-animate-top="50px" data-animate-time="0.2s" data-animate>Animation on scroll</h1>