Day 2 of #javascript30 is using CSS transform to rotate the hands on a clock.
Manipulating CSS
A HTMLElement has a style property that can be accessed and manipulated like this for instance:
document.querySelector('.second-hand').style.transform = `rotate(${secondsDegrees}deg)`;
Vanilla JS has a toggle()
that works just like jQuery's toggleClass()
. In fact the classList has a couple of very handy functions that are a lot like stuff jQuery will give you.
Template Literals
The string in back-ticks in the code above is using a Template Literal and I love them. They make it so much easier to write some HTML in JS and to get variable in strings without concatenating them. To use a variable in the string, use the ${yourVar}
notation. You can even do stuff like this:
var firstVar = 2;
var secondVar = 2;
console.log(`${firstVar} plus ${secondVar} is ${firstVar + secondVar}`);
and that will output "2 plus 2 is 4". There is also Tagged Template Literals - that will let you apply a function to the variables you "pass in" to the template literal. Pretty neat.