I have a SVG animation:
html, body {
background: #000;
}
.hb {
width: 40px;
margin: 0 auto;
display: block;
}
<svg class="hb" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" stroke="#eee" stroke-width=".6" fill="rgba(0,0,0,0)" stroke-linecap="round" style="cursor: pointer">
<path d="M2,3L3.5,3L5,3M2,5L8,5M5,7L6.5,7L8,7">
<animate dur="0.2s" attributeName="d" values="M2,3L3.5,3L5,3M2,5L8,5M2,7L5,7L8,7;M3,3L4,4L5,5M3,7L7,3M5,5L6,6L7,7" fill="freeze" begin="start.begin" />
<animate dur="0.2s" attributeName="d" values="M3,3L4,4L5,5M3,7L7,3M5,5L6,6L7,7;M2,3L3.5,3L5,3M2,5L8,5M5,7L6.5,7L8,7" fill="freeze" begin="reverse.begin" />
</path>
<rect width="10" height="10" stroke="none">
<animate dur="2s" id="reverse" attributeName="width" begin="click" />
</rect>
<rect width="10" height="10" stroke="none">
<animate dur="0.001s" id="start" attributeName="width" values="10;0" fill="freeze" begin="click" />
<animate dur="0.001s" attributeName="width" values="0;10" fill="freeze" begin="reverse.begin" />
</rect>
</svg>
The animation works fine when interacting with mouse clicks. However, I want to use jQuery to trigger the animation with id="reverse"
. How can I do so?
My idea is: that when I first click the SVG icon, it starts to play a 0.2s animation and then shows the menu DIV. After the menu DIV's close button (#btn_menu_close
) is clicked, the reverse SVG animation is played to change the SVG icon back to the original state.
My jQuery code (I am not using $
symbol as I am using it in WordPress):
jQuery('.hb').click(function() {
function showMenu() {
jQuery('.body-menu').fadeIn();
}
setTimeout(showMenu, 200);
});
jQuery('#btn_menu_close').click(function() {
jQuery('.body-menu').fadeOut();
// WHAT SHOULD I WRITE HERE to trigger the reverse animation?
});
You can use $("#reverse")[0].beginElement();
to achieve your goal
Working snippet:
$("#reverse")[0].beginElement();
html, body {
background: #000;
}
.hb {
width: 40px;
margin: 0 auto;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<svg class="hb" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" stroke="#eee" stroke-width=".6" fill="rgba(0,0,0,0)" stroke-linecap="round" style="cursor: pointer">
<path d="M2,3L3.5,3L5,3M2,5L8,5M5,7L6.5,7L8,7">
<animate dur="0.2s" attributeName="d" values="M2,3L3.5,3L5,3M2,5L8,5M2,7L5,7L8,7;M3,3L4,4L5,5M3,7L7,3M5,5L6,6L7,7" fill="freeze" begin="start.begin" />
<animate dur="0.2s" attributeName="d" values="M3,3L4,4L5,5M3,7L7,3M5,5L6,6L7,7;M2,3L3.5,3L5,3M2,5L8,5M5,7L6.5,7L8,7" fill="freeze" begin="reverse.begin" />
</path>
<rect width="10" height="10" stroke="none">
<animate dur="2s" id="reverse" attributeName="width" begin="click" />
</rect>
<rect width="10" height="10" stroke="none">
<animate dur="0.001s" id="start" attributeName="width" values="10;0" fill="freeze" begin="click" />
<animate dur="0.001s" attributeName="width" values="0;10" fill="freeze" begin="reverse.begin" />
</rect>
</svg>