On page reload its happening. After shaking first time if I click inside the div, its still shaking. Clicking inside the div should not add shake effect. What is my issue?
$(document).mouseup(function (e) {
if ($(e.target).closest("#inside_box").length === 0) {
document.addEventListener("click", (e) => {
e.preventDefault();
$("#inside_box").addClass('shake');
});
document.addEventListener("animationend", (e) => {
$("#inside_box").removeClass('shake');
});
}
});
#inside_box {
background: #f00;
height:100px;
width:100px;
}
.shake {
animation-name: shake;
animation-duration: 1s;
animation-fill-mode: both;
}
@keyframes shake {
0%, 100% {
transform: translateX(0);
}
10%, 30%, 50%, 70%, 90% {
transform: translateX(-10px);
}
20%, 40%, 60%, 80% {
transform: translateX(10px);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div id="box">
<div id="inside_box">
Content
</div>
</div>
</body>
Best to do this with a single click listener and not add additional event listeners within an event handler
Working example:
$(document).click(function(e) {
if (!$(e.target).closest("#inside_box").length) {
$("#inside_box").addClass('shake').on("animationend", function(e) {
$(this).removeClass('shake').off("animationend");
});
}
});
#inside_box {
background: #f00;
height:100px;
width:100px;
}
.shake {
animation-name: shake;
animation-duration: 1s;
animation-fill-mode: both;
}
@keyframes shake {
0%, 100% {
transform: translateX(0);
}
10%, 30%, 50%, 70%, 90% {
transform: translateX(-10px);
}
20%, 40%, 60%, 80% {
transform: translateX(10px);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div id="box">
<div id="inside_box">
Content
</div>
</div>
</body>