JavaScript DOM & Animation Lab

1. onclick

<button onclick="sayHi()">Click</button> function sayHi(){ alert("Hi!"); }

2. innerText

document.getElementById("title").innerText = "Changed!";

Hello

3. img.src

document.getElementById("pic").src = "image2.png";

4. style.property

element.style.color = "red"; element.style.backgroundColor = "yellow";
Watch me change

5. CSS vs JavaScript

color: red; → element.style.color = "red"; background-color: yellow; → element.style.backgroundColor = "yellow"; width: 200px; → element.style.width = "200px"; height: 100px; → element.style.height = "100px"; font-size: 20px; → element.style.fontSize = "20px"; border-radius: 20px; → element.style.borderRadius = "20px";
Remember: always use quotes → "200px"

6. Full Example

let div = document.getElementById("demoBox"); div.style.color = "red"; div.style.backgroundColor = "yellow"; div.style.width = "200px"; div.style.height = "100px"; div.style.fontSize = "20px"; div.style.fontWeight = "bold"; div.style.border = "3px solid black"; div.style.borderRadius = "20px";
Box

7. Variables + Strings

let w = 200; div.style.width = w + "px";
"px" is text → called a string

8. setInterval

setInterval(move, 1000);
Interval = time between repeats 1000 = once per second

9. Movement


let x = 0; let loop; function move(){ x += 5; if(x > 400){ clearInterval(loop); } moveBox.style.marginLeft = x + "px"; } function startMove(){ clearInterval(loop); loop = setInterval(move, 50); } function stopMove(){ clearInterval(loop); } function reset(){ x = 0; moveBox.style.marginLeft = "0px"; }

10. Sprite Animation



let frame = 0; function animate(){ frame++; if(frame > 5){ frame = 0; } player.src = "animations/man-walking/" + frame + ".png"; } function startAnim(){ loop = setInterval(animate, 100); } function stopAnim(){ clearInterval(loop); }

Challenge