Connor McLeod Connor McLeod - 4 months ago 8
jQuery Question

jQuery animation after removing elements

I have the following HTML and CSS:

<div id="categories">
<h3 id="sports">Sports</h3>

<h3 id="videogames">Video Games</h3>

<h3 id="music">Music</h3>

<h3 id="web">Web</h3>
</div>

#categories {
left: 50%;
top: 50%;
position: absolute;
-webkit-transform: translate3d(-50%, -50%, 0);
-moz-transform: translate3d(-50%, -50%, 0);
transform: translate3d(-50%, -50%, 0);
}

#categories > h3 {
display: inline;
}


The
h3
elements are displaying inline and centered. I have the following code in jQuery that when you click an
h3
element, the other elements fade out. It works well to remove the elements, but once they disappear, the selected element just suddenly flashes into the center (which is where I want it) but is there a way to animate this? Make it a smoother transition?

$("#categories h3").click(function(){
if(this.id == "sports"){
$("#videogames").fadeOut(500);
$("#music").fadeOut(500);
$("#web").fadeOut(500);
}
})

Answer

Use transition, much better.

$("#categories h3").click(function(){
    if(this.id == "sports"){
        $("#videogames, #music, #web").css({opacity: 0});
    }
});
#categories {
    left: 50%;
    top: 50%;
    position: absolute;
    -webkit-transform: translate3d(-50%, -50%, 0);
    -moz-transform: translate3d(-50%, -50%, 0);
    transform: translate3d(-50%, -50%, 0);
}

#categories > h3 {
    display: inline;
    transition: opacity .3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="categories">
        <h3 id="sports">Sports</h3>

        <h3 id="videogames">Video Games</h3>

        <h3 id="music">Music</h3>

        <h3 id="web">Web</h3>
</div>