Search code examples
javascriptjqueryhtmlanimate-on-scrollaos.js

Use AOS.js with class instead of data attribute


I want to use AOS.js on my site but I have no option to add the necessary data attributes to the DIVs of the page.

Here's the markup from the docs (https://michalsnik.github.io/aos/):

<div data-aos="fade-up" data-aos-duration="3000">
    ...
</div>

My markup looks like this:

<div class="aos-fade-up aos-duration-3000">
    ...
</div>

Is there any way to use AOS.js with only classes?

I found a similar question while researching: Having trouble adding aos.js using classes But there is no answer to that.

Here's the code from the other question but that doesn't work:

$('.aos-fade-up').each(function(i) {
    $(this).attr('data-aos', 'fade-up');
});

Any ideas?


Solution

  • You can give this snippet a try :

    <script>
            function ismatch(str){
                var ret = null;
                var tab = ['data-aos_', 'data-aos-delay_', 'data-aos-duration_', 'data-aos-easing_'];
                Object.values(tab).forEach( function (value) {
                    if (String(str).match(value)){
                        ret = str.split('_');
                        return false;
                    }
                });
                return ret;
            }
            jQuery(document).ready(function ($) {
                $('.some-class').each(function () {
                    var $this = $(this);
                    var tab = $this.attr('class').split(' ');
                    var keep;
                    Object.values(tab).forEach(function (item) {
                        var ello = ismatch(item) 
                        if (ello !== null)
                            $this.attr(ello[0], ello[1]);
                        });
                        
                    });
                    AOS.init();
                });                     
        </script>
    

    Usage :

    <div class="some-class data-aos_fade-down data-aos-delay_100 data-aos-duration_800"></div>```