


Khusboo Tayal
JavaScript in the browser interacts not just with the HTML (DOM) but also with the browser itself through the BOM (Browser Object Model). This chapter explores how JavaScript handles user interaction, browser control, and timing.
The BOM lets JavaScript interact with the browser window and perform actions like opening/closing tabs, navigating pages, and detecting screen size.
Key Objects:
Example:
console.log(window.innerWidth); // Width of browser console.log(navigator.userAgent); // Browser info console.log(location.href); // Current URL
Events are actions or occurrences (like a user clicking a button) that can be handled with JavaScript.
Common Event Types:
Adding Event Listeners:
document.getElementById("btn").addEventListener("click", function () {
alert("Button clicked!");
});Event Object:
Each handler receives an event object with details:
element.addEventListener("click", function(e) {
console.log(e.target); // element clicked
});JavaScript allows you to delay or repeat actions with setTimeout and setInterval.
setTimeout: Run code after a delay
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);setInterval: Repeat code every interval
const intervalId = setInterval(() => {
console.log("Repeats every 1 second");
}, 1000);
// To stop it
clearInterval(intervalId);
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM is ready!");
});You can use BOM methods like:
window.open("https://example.com");
window.close();
window.scrollTo(0, 500);
Note: Some of these are restricted for security or user experience reasons.
JavaScript in the browser isn't limited to HTML manipulation. The BOM enables interaction with the browser environment, while events and timers make applications dynamic and responsive. Mastering these is key to building interactive web apps.