Reputation: 489
So I have this arrow SVG which I am using for hiding/displaying a div. How can I rotate that arrow back and forth on every click?
Html:
<md-icon md-svg-icon="assets/svg/down-arrow.svg"></md-icon>
SVG:
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="arrow" x="0px" y="0px" viewBox="0 0 386.257 386.257" style="enable-background:new 0 0 386.257 386.257;" xml:space="preserve" width="24px" height="24px">
<polygon points="0,96.879 193.129,289.379 386.257,96.879 " fill="#e18327"/>
</svg>
Upvotes: 2
Views: 10295
Reputation: 89750
It is very simple to do with CSS Transforms and JavaScript. Use JS to listen for the click event and when it happens toggle a class (which has the CSS transform: rotate
) on or off.
In the below snippet, I've used an inline SVG (that is, SVG within the md-icon
tag as the SVG file is not hosted anywhere to link to) but you can do that with external SVG files also. Just add the listener and set the class to the md-icon
element or whatever is the element that contains the SVG.
document.querySelector('md-icon').addEventListener('click', function() {
this.classList.toggle('rotated');
});
.rotated {
transform: rotate(-90deg);
}
md-icon {
display: inline-block;
transition: all 1s;
}
<link href="http://rawgit.com/angular/bower-material/master/angular-material.min.css" rel="stylesheet"/>
<md-icon md-svg-icon='assets/svg/down-arrow.svg'>
<?xml version="1.0" encoding="iso-8859-1" ?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="arrow" x="0px" y="0px" viewBox="0 0 386.257 386.257" style="enable-background:new 0 0 386.257 386.257;" xml:space="preserve" width="24px" height="24px">
<polygon points="0,96.879 193.129,289.379 386.257,96.879 " fill="#e18327" />
</svg>
</md-icon>
We can of-course use two different SVG files and change the source (from down arrow to right arrow) on click but that wouldn't produce a smooth transition like the below snippet.
Another choice would have been to use SMIL animations but they are being deprecated and hence it is better to use CSS transforms.
Upvotes: 3