Monday, May 16

Javascript - The DOM





DOM - Document Object Model

// Create a Simple Object
var object = {};

// It can have key value pairs
var object = {
   name : "Adam"
}

// An object can have another object
var object = {
   name:"Adam",
   address : {
      street : "Florida"
   }
}

// To access the values, use the dot notation
var name = object.name
alert(name);

Dom Functions
//Create a paragraph tag
var paragraph = document.createElement("p");

// Add a text to the paragraph
paragraph.textContent = "The DOM is ready to be viewed";

//Add text to body
document.body.appendChild(paragraph);


Event Listeners
//Create a Div element
var div = document.createElement("DIV");

// Set the height of the Element
div.style.height = "100vh";

//Append Element to DOM
document.body.appendChild(div);

// Add Event Listener to Element
div.addEventListener('mousemove', function(event){
    console.log(event);
 
    // Display client x and client y
   var x = event.clientX;
   var y = event.clientY;
   div.textContent = x + ', ' + y;
   div.style.backgroundColor = 'rgb(' + x + ', ' + y + ', ' + 100)';

});


Refactoring your Code
function fullScreen(element){
   //Create a element
   var newElement = document.createElement(element);

   // Set the height of the Element
   newElement.style.height = "100vh";

   //Append Element to DOM
   document.body.appendChild(newElement);

    return newElement;
}

function input(inputType, DOMElemenet, callback){
   // Add Event Listener to Element
    DOMElemenet.addEventListener(inputType, function(event){
        var x = event.clientX;
        var y = event.clientY;
        callback(DOMElement, x, y);
    });
}

function output(element, x, y){
    element.textContent = x + ', ' + y;
    element.style.backgroundColor = 'rgb(' + x + ', ' + y + ', ' + 100)';
}

input('mousemove', fullScreen('DIV'), output);

// So which function's you can change arguments

input('click', fullScreen('DIV'), output);





Helper Functions
SetInterval

function time(){
   var date = new Date();
   var hours = date.getHours();
   var minutes = date.getMinutes();
   var seconds = date.getSeconds();
   var arr = [hours, minutes, seconds].map(function(num){
      return num < 10 ? '0' + num: String(num);
   });


   hours = arr[0];
   minutes = arr[1];
   seconds = arr[2];

   return hours + minutes + seconds;
}

function output(time){
  var color = "#" + time;
  document.body.bgColor = color;
  document.body.textContent = color;
}

function startClick(callback, name){
  document.body.addEventListener('dblclick', function(event){
    callback(name);
  });
}

function stopClick(callback, name){
  document.body.addEventListener('click', function(event){
    callback(name);
  });
}


function init(){
   var tick = setInterval(function(){
     output(time());
   },  1000);

   stopClick(clearInterval, tick);
   startClick(init);
}

init();

Be the first one to Comment!!!

Post a Comment