Posted by & filed under JavaScript, web developing.

Recently I had to implement some SVG into JavaScript for a yourtube placeholder for lazy loading and it turned out to be quite easy. The main thing you need to be aware of is the different namespace which svg is using. After that it becomes very easy. You can run the following in the console and see the youtube play button.

const svgNS = '';

const playButton = document.createElementNS(svgNS, 'svg');
playButton.setAttribute('fill', 'red');
playButton.setAttribute('width', '72');
playButton.setAttribute('height', '72');
playButton.setAttribute('viewbox', '0 0 72 72');
playButton.setAttribute('style', 'position: absolute; top: 50%; left: 50%; transform: translate(-36px, -36px)');

const rect = document.createElementNS(svgNS,'rect');
rect.setAttribute('fill', 'white');
rect.setAttribute('x', '10');
rect.setAttribute('y', '15');
rect.setAttribute('width', '52');
rect.setAttribute('height', '42');

const youtube = document.createElementNS(svgNS,'path');
youtube.setAttributeNS(null, 'd', 'M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z');
youtube.setAttribute('transform', 'scale(3)');



Using SVG in this way makes it also more easy to create interactive SVG’s, it is easy to add an id to each SVG element and add some behavour.

Comments are closed.