# DOM as JavaScript's gateway into HTML

Sunday, Jul 12, 2020
Frontend

Ok, now the big moment - how to make the pages interactive. It's done using DOM - Document Object Model.

## What is DOM?

DOM is a representation of the webpage in the form of JavaScript's object. All HTML elements (body, divs, paragraphs, images etc) are nodes of the object. This is cool since changing something on the page now means updating the object:

• adding a new element means adding a new key:value pair to the object
• changing something in the existing element means updating an existing key:value pair

## So how do I connect?

Let's see with a simple example, where we want to change the background color of a page when a button is clicked.

1. Give an id to the element that you want to add interactivity to. There are other ways but we will focus on id approach for now:
...
<button id="bg-btn">Change Background Color</button>
...

1. Using <script> tag just before closing body tag </body>, connect to the javascript file:
...
<script src="index.js"></script>
</body>

1. In javascript, document is the main object using which we access the DOM. For grabbing the element by id, we use getElementById method:
let myBtn = document.getElementById("bg-btn");

1. Add event listener to the element using addEventListener method:
myBtn.addEventListener("click", function() {
...
})


addEventListener has two arguments. First is the event name, click in the example above and second is the function to be called when the event mentioned in the first argument happens.

## Change background color

Putting the above steps together:

let myBtn = document.getElementById("bg-btn");
let colorArray = [ '#E6B333', '#3366E6', '#999966', '#99FF99', '#B34D4D'];

myBtn.addEventListener("click", function() {
let color = colorArray[getRandomInt(colorArray.length)];
document.body.style.background = color;
})

function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}


And voila!