JavaScript Browser Object Model - Exercise 3

Attach a listener to the window's resize event. The handler runs whenever the viewport changes, so it can update measurements or responsive UI state.

javascript

window.addEventListener('resize', () => {
  console.log(window.innerWidth, window.innerHeight);
});

Pass the same function reference to removeEventListener() that you used when adding the listener.

javascript

function handleResize() {
  console.log('resized');
}

window.addEventListener('resize', handleResize);
window.removeEventListener('resize', handleResize);

It schedules visual updates to run before the browser's next repaint, which helps animations stay smooth and efficient.

javascript

function draw() {
  box.style.transform = 'translateX(20px)';
}

requestAnimationFrame(draw);

Store the ID returned by requestAnimationFrame() and pass it to cancelAnimationFrame().

javascript

const frameId = requestAnimationFrame(draw);
cancelAnimationFrame(frameId);

It can provide a browser-supplied platform string such as the operating system family or device class, but the value is not guaranteed to be consistent across browsers.

javascript

console.log(navigator.platform);

User-agent strings can change or be spoofed, so feature detection is usually more reliable because it checks whether the needed capability actually exists.

javascript

if ('geolocation' in navigator) {
  console.log('Geolocation is available');
}

screen.height refers to the physical display area, while the viewport height reflects only the page's visible content area inside the browser window, which is often smaller because of tabs, toolbars, and other browser UI.

javascript

console.log(screen.height);
console.log(window.innerHeight);

window.print() opens the browser's print dialog for the current document. It should normally run after a user action, and print-specific CSS can control what appears on paper.

javascript

window.print();

Listen for beforeunload and call preventDefault() when there is unsaved work. The browser decides whether to show a generic warning message.

javascript

window.addEventListener('beforeunload', (event) => {
  if (formIsDirty) {
    event.preventDefault();
    event.returnValue = '';
  }
});

Permissions such as notifications, location, or camera access can be granted, denied, or changed by the user at any time, so your code should always handle every possible permission state.

javascript

navigator.permissions.query({ name: 'geolocation' }).then((result) => {
  console.log(result.state); // 'granted', 'denied', or 'prompt'
});
All sections expanded. Activate the control to collapse all sections.