Repozytorium Web Developera

Archiwum z lat 2013-2018, treści mogą być nieaktualne.

DOM, BOM & Web APIs

The BOM (Browser Object Model) consists of objects: navigator, history, screen, location and document which are children of window. In the document node is the DOM (Document Object Model), the document object model, which represents the contents of the page. You can manipulate it using JavaScript. Source.

window vs window.document/document

window object doesn't have all the methods which has document object. document object has the whole DOM.

window.document/document methods

To get an element:


document.getElementById(ID)
document.getElementsByTagName(ELEMENT_TYPE)
document.getElementsByClassName(CLASS) // But it's only in IE9+ - whereas .querySelectorAll() is in IE8.
document.querySelector(SELECTOR)
document.querySelectorAll(SELECTOR)

To create an element:


document.createElement(ELEMENT_TYPE) // ex. 'img', 'div'

Some not popular methods:


document.activeElement // gets an focused element
document.readyState // is document loaded?

Child can be a Text node or an Element node. firstElementChild or lastElementChild will return only Element nodes. Similar methods without Element in name may also return a Text node.

  • .childElementCount
  • .firstElementChild
  • .lastElementChild
  • .previousElementSibling
  • .nextElementSibling

Node types and Element type

Node in not always an Element. There are several types of Nodes (like a Text Node). Element is one of them.

Element methods

Every element has some similar method to the document object. Especially for searching for nodes.

To append an element to another element:


element.appendChild(ELEMENT)

To set an attribute on element:


element.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE)

Some attributes you can set up directly:


img.src = URL

Events

To create a new type of event: event = document.createEvent('HTMLEvents').

To init an event: event.initEvent('dataavailable', true, true).

To listen for an event: document.addEventListener(eventName, callback). For example, to listen for invalid input and scroll to it:


document.addEventListener('invalid', (event) => {
  event.target.scrollIntoView(false)
}, true)

Scroll

Browser natively allows to scroll smoothly:


window.scroll({top: 0, left: 0, behavior: 'smooth' })

window.navigator

The navigator object has properties which specify user browser.

Web Share API navigator.share

Used to share URL/content using native capabilities of the host platform. Blog post on Google Web Fundamentals.


if (navigator.share) {
  navigator.share({
      title: 'Web Fundamentals',
      text: 'Check out Web Fundamentals — it rocks!',
      url: 'https://developers.google.com/web',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
}

MediaDevices

MediaDevices is part of WebRTC API. MediaDevices on MDN.

Get access to device

The MediaDevices.getUserMedia() method is used to prompt the user for permission to use a media input which produces a MediaStream with tracks containing the requested types of media.

For example, to get rear camera and show it's stream in an video element:


const video = document.getElementById("video")
const constraints = {
    advanced: [{
        facingMode: "environment"
    }]
}
navigator.mediaDevices
    .getUserMedia({
        video: constraints
    })
    .then((stream) => {
        video.src = window.URL.createObjectURL(stream)
        video.play()
    })

Where environment is one of facingMode types: facingMode on MDN.

You can also check MediaRecorder API and WebRTC.

Call camera from file input

By using FileReader interface and it's method readAsDataURL you can get access to an image from an input and display it in image element. readAsDataURL on MDN


<input type="file" accept="image/*" capture="user" onchange="previewFile()"> 

function previewFile() {
  var preview = document.querySelector('img')
  var file = document.querySelector('input[type=file]').files[0]
  var reader = new FileReader()

  reader.addEventListener('load', function () {
    preview.src = reader.result
  }, false)

  if (file) {
    reader.readAsDataURL(file)
  }
}

Enumerate devices

You can enumerate through available devices by using the enumerateDevices method.


var enumeratorPromise = navigator.mediaDevices.enumerateDevices()

To list available devices you can write:


if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.")
  return
}

// List cameras and microphones.

navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    devices.forEach(function(device) {
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId)
    })
  })
  .catch(function(err) {
		console.log(err.name + ": " + error.message)
  })

Useful links