Reputation:
Thanks for reading. I am trying to check a function whether true of false. If false, I would like to change the border color to red, appear and disappear and appear and disappear in 2 seconds. I just tried the css animation to achieve it, but it only appear one time. https://codesandbox.io/s/38qvr0j3lp
I wonder if there is a way using CSS to achieve it. Any help would be appreciated.
Upvotes: 0
Views: 1122
Reputation: 18649
Here's a little demo - on click I'm adding an animation
(via keyframes
instead of transition
) to the button element.
The keyframe animation begins with a red border, and has a transparent border in the middle. By using this in conjunction with steps(1)
, the animation is treated like it consists of two frames (at 0%
and 50%
), alternating transparent and red. I run this animation twice (that's the 2
) over 1 second each time (that's the 1s
).
In the JS, note that I'm removing the blink
class and readding it 10ms later in case it's already there. You can't retrigger a CSS keyframe animation without removing and readding the property.
function blink(el) {
el.classList.remove("blink")
setTimeout(function() {
el.classList.add("blink")
}, 10);
}
button {
border: 1px solid transparent;
outline: none;
}
.blink {
animation: border-blink 1s steps(1) 2;
}
@keyframes border-blink {
0% {
border-color: red;
}
50% {
border-color: transparent;
}
}
<button onclick="blink(this)">Click Me</button>
Upvotes: 2
Reputation: 21846
Fixed the code in your code sandbox with a totally React approach.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false
};
}
showErrorSignal() {
this.setState({ error: true });
setTimeout(() => this.setState({ error: false }), 500);
setTimeout(() => this.setState({ error: true }), 1000);
setTimeout(() => this.setState({ error: false }), 1500);
}
render() {
const styles = {
error: {
borderWidth: 5,
borderColor: "red"
}
};
return (
<div className="App" style={this.state.error ? styles.error : undefined}>
<h1>Hello CodeSandbox</h1>
<button onClick={() => this.showErrorSignal()}>
show error signal
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.App {
font-family: sans-serif;
text-align: center;
border: 3px solid #d5edeb;
transition-property: border-color, border-width;
transition-duration: 500ms;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
Upvotes: 0