AndrewLeonardi AndrewLeonardi - 3 months ago 12
CSS Question

Load CSS element on click?

I have a "loading" element that I want to display when a user clicks a button. See the JsFiddle.

I'm trying to figure out if its possible to have this CSS animation load when a user clicks a button. I've tried to delay the CSS from loading but that does not accomplish what I'm after. How do I change my code to make it load the animation on click?



body { min-height: 100%; background: tomato }
h1 {
position: absolute;
left: 50%;
margin-left: -1.9em;
color: beige;
font: 800 900% Baskerville, 'Palatino Linotype', Palatino, serif;
}
h1:before {
position: absolute;
overflow: hidden;
content: attr(data-content);
color:#34495e;
max-width: 4em;
-webkit-animation: loading 5s linear;
}
@-webkit-keyframes loading {
0% {
max-width : 0
}
}

<h1 data-content="Loading Results">Loading Results</h1>




Answer

try the code below, but also check out my 5 mins intro to CSS animation http://www.coding-dude.com/wp/web-design/css/5-min-css-animation-beginner-tutorial/

var loadButton = document.getElementById("load");
var title = document.getElementById("title");
loadButton.addEventListener("click",function(e){
  e.preventDefault();
  title.classList.toggle("loading");  
})
body { min-height: 100%; background: tomato }
h1 {
    position: absolute;
    left: 50%;
    margin-left: -1.9em;
    color: beige;
    font: 800 900% Baskerville, 'Palatino Linotype', Palatino, serif;
}
h1:before {
    position: absolute;
    overflow: hidden;
    content: attr(data-content);
    color:#34495e;
    max-width: 4em;
}

.loading:before{
  -webkit-animation: loading 5s linear;  
}
@-webkit-keyframes loading {
    0% {
        max-width : 0
    }
}
<button id="load">start loading</button>
<h1 id="title" data-content="Loading Results">Loading Results</h1>