Skip to content
Advertisement

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;"
        onscroll="animateAfterPosition(200)"
        data-animate-left="50px" data-animate-top="50px" 
        data-animate-time="0.2s">Animation on scroll</h1>

This is my JavaScript

function animateAfterPosition(scroll) {
console.log(scroll);
    function(){ 
        if (window.scrollY <= scroll) {
            this.classList.add('animateAfterPosition');
        } else {
            this.classList.remove('animateAfterPosition');
        }}

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?

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

Advertisement

Answer

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>
</body>

Fiddle: https://jsfiddle.net/rafonzoo/phmg0u46/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement