Web Cartography 6

JavaScript Objects & BOM/DOM

Object oriented, remember?

  • methods via object.method()
  • properties via object.property
  • references to data
  • examples?
var x = [1, 2, 3];
var y = x;
console.log(x);
x.reverse();

x[0] = 0;
console.log(y); // what would be the result?
console.log(y.length);
var str = "I'm a string",
    strObj = new String("I'm a string");

console.log(typeof(str));
console.log(typeof(strObj));

console.log(typeof(str) == typeof(strObj));
console.log(typeof(str) === typeof(strObj));

Exercise

  • convert string to uppercase
  • with "I'm a 1000 years old" string, do the following:
    • turn it into an array
    • identify the only numeric item (not using array indices)
    • subtract any number you want from that item
    • turn the array back into the string
  • what's the position of the first vowel in your surname?

Browser Object Model

collection of objects made available by the browser

browser dependent

most important (for us): window, document (DOM)

Exercise

  • count all the <div> elements in the webpage you've made
  • find one element by its id and try to change its color
  • choose a part of your webpage and try to remove it from DOM
  • try to create new DOM Element and append it to the <body>

Events

clicks

keystrokes

mouse movement

...

<a href="http://google.com" onclick="alert('Goodbye');">Google</a>

-- or --
<!-- html -->
<a href="http://google.com">Google</a>
<!-- js -->
document.getElementsByTagName("a")[0].onclick = function() {
    alert("Goodbye");
};

-- or -- allows you to register more than one handler
<!-- html -->
<a href="http://google.com">Google</a>
<!-- js -->
document.getElementsByTagName("a")[0].addEventListener("click", function() {
    alert("Goodbye");
});

Exercise

  • try to change color of the text with mouseover event; don't forget to restore its original value
  • try to set focus to the next input when the length of the current equals 3 with some key* event

Web Cartography 6: JavaScript Objects & BOM/DOM

By Michal Zimmermann

Web Cartography 6: JavaScript Objects & BOM/DOM

  • 1,384