David Diefenderfer
David Diefenderfer

Reputation: 43

Regarding JavaScript, Is there an easier way to code this?

I'm learning JavaScript in depth and I'm wondering if i've coded this the best way possible? I tried creating my own fade out animation based off of data attribute values. Please let me know if theres a way to simplify this. Thanks

Don't mention jQuery please. I'm trying to learn JavaScript, I'm well aware that jQuery already made this.

HTML

<div id="box" style="background-color: black; width: 100px; height: 100px;"></div>

<div data-action="fadeout" style="background-color: red; width: 100px; height: 100px;"></div>

<div data-action="fadeout" style="background-color: green; width: 100px; height: 100px;"></div>

<div data-action="fadut" style="background-color: green; width: 100px; height: 100px;"></div>

JavaScript

var x = document.querySelectorAll("[data-action]");
console.log(x);

for (i = 0; i < x.length; i++){

    var j = x[i];

    if (j.getAttribute("data-action") === "fadeout"){
        j.addEventListener("click", function(){
            fadeout(this);
        });
    }

}

function fadeout(x){

    var i = 1;
    x.style.position = "relative";

    fade();

    function fade(){
        console.log("hi");
        if (i > 0){

            x.style.opacity = i.toString();

            setTimeout(function(){
                fade();
                i -= .1;
            }, 50);

        } 
        else{
            x.style.display = "none";
        }
    }


}

http://jsfiddle.net/qdjLyg2o/

Upvotes: 2

Views: 70

Answers (1)

Dai
Dai

Reputation: 155065

CSS animations or CSS transitions would be a better way to implement a fade effect: they would be smoother and use less CPU, and mean less code for you too. Generally avoid animations in JavaScript unless they absolutely cannot be accomplished using CSS's animation or transition repertoire.

*[data-action="fadeout"] {
    opacity: 1.0;
    transition: opacity 0.5s ease-in-out; /* your code changed opacity by 0.1 every 50ms, that's 0.0-1.0 over 500ms */
}
*[data-action='fadeout'].clicked {
    opacity: 0.0;
}

Then use JavaScript to set the .clicked class:

var divs = document.querySelectorAll("[data-action='fadeout']");
for(var i=0; i < divs.length; i++) {
    divs[i].addEventListener("click", function(){
        this.className = "clicked";
    });
}

Upvotes: 1

Related Questions