Search code examples
htmljquerycustom-data-attribute

Add class using data attribute value while document ready


I'm trying to use data attributes for my HTML. I want to add a class while loading the page.

jQuery

var $this = $(this);
$(document).ready(function(){
    $("[data-load-animation]").each(function() {
        $this.hide();
        var cls = $this.attr("data-load-animation");
        console.log("console: "+cls);
        $this.addClass(cls);    
    })
})

Here is my JSFiddle Demo

I need to add a class bounce for every element having this data attribute, I think... but I'm not sure why it's not working.


Solution

  • The problem seems to be the $this reference, in your case it is referring the window object.

    Instead you need to refer the current [data-load-animation] element, so define it within the each() loop

    $(document).ready(function () {
        $("[data-load-animation]").each(function () {
            var $this = $(this);
            $this.hide();
            var cls = $this.data("loadAnimation");
            console.log("console: " + cls);
            $this.addClass(cls);
        })
    })