SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
JAVASCRIPT
#burningkeyboards
@denis_ristic
JAVASCRIPT
INTRO
▸ JavaScript is a programming language used to make web pages
interactive.
▸ In our case it runs on your visitor's computer (browser).
▸ JavaScript support is built right into all the major web browsers.
▸ JavaScript is an interpreted language, so no special program is required
to create usable code.
▸ JavaScript is used in HTML by inserting a <script> tag:
▸ JavaScript code is written inside <script> tag (bad practice)
▸ .js files are linked using <script src=“link/file.js”>
2
JAVASCRIPT
DOCUMENT OBJECT MODEL
▸ The HTML DOM is a
standard object model
and programming interface for
HTML
▸ It defines:
▸ The HTML elements as objects
▸ The properties of all HTML
elements
▸ The methods to access all HTML
elements
▸ The events for all HTML elements
3
JAVASCRIPT
COMMON DOM EVENTS
▸ Here is a list of some common HTML events:
▸ onchangeAn HTML element has been changed
▸ onclick The user clicks an HTML element
▸ onmouseover The user moves the mouse over an HTML element
▸ onmouseout The user moves the mouse away from an HTML element
▸ onkeydown The user pushes a keyboard key
▸ onload The browser has finished loading the page
▸ onfocus An element has received focus
▸ onblur An element has lost focus
4
JAVASCRIPT
CONSOLE
▸ The Console object provides access to the browser's
debugging console.
▸ Docs:
▸ https://developer.mozilla.org/en-US/docs/Web/API/Console
▸ https://developers.google.com/web/tools/chrome-devtools/
console/
▸ How to open Console in Google Chrome:
▸ Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).
5
JAVASCRIPT
CONSOLE
▸ Methods:
▸ console.error()
▸ console.warn()
▸ console.info()
▸ console.log()
▸ console.time() & console.timeEnd() & console.timeStamp()
▸ console.profile() & console.profileEnd()
▸ console.clear()
▸ console.dir() & console.dirXml()
▸ console.group() & console.groupEnd() & console.groupCollapsed()
▸ console.count()
▸ console.assert()
▸ console.trace()
6
JAVASCRIPT
VARIABLES, OPERATORS & COMMENTS
var myVariable = 'BurningKeyboards';
myVariable = 'Perpetuum';
var myIntVariable = 10;
var myBoolVariable = true;
var myArrayVariable = [1, 'Bob', 'Steve', 10];
var myObjectVariable = document.querySelector('h1');
var add = 6 + 9;
var concat = "Hello " + "world!";
var subtract = 9 - 3;
var multiply = 8 * 2;
var divide = 9 / 3;
/*
Everything in between is a comment.
*/
// This is a one line comment
7
JAVASCRIPT
CONDITIONALS
/* Multi
If, ElseIf, Else statements */
var a = 1;
var b = 2;
var c = 3;
if( a > b ) {
console.log('the if is true!');
} else if(a > c) {
console.log('OK, THIS if is True!');
} else {
console.log('None of these were true');
}
// Ternary operators. same as if else
var a = 1;
var b = 2;
a === b ? console.log('The statement is true') : console.log('The statement is false');
// switch statements
var a = 4;
switch (a) {
case "Oranges":
console.log("Orange? really?");
break;
case 1:
console.log("a is equal to 1.");
break;
default:
console.log("I run if no one else is true.");
}
8
JAVASCRIPT
LOOPS
// while loop
var i = 0;
while( i < 10 ) {
console.log(i);
i += 1;
}
// do while loop
var i = 0;
do {
console.log(i);
i += 1;
} while ( i < 10 )
// for loop
for ( var i = 0; i < 10; i++ ) {
console.log(i);
}
// for in statements
var obj = {a:1, b:2, c:3};
for ( var prop in obj ) {
// check if property is inherited or not
if(obj.hasOwnProperty(prop)) {
console.log("obj." + prop + " = " + obj[prop]);
}
}
9
JAVASCRIPT
ARRAYS
// create an empty array
var myArray = [];
// create array with items. Can store any type
var myOtherArray = [myArray, true, "A random string"];
// call specific value in an array
myOtherArray[0];
// change value for this item
myOtherArray[0] = false;
// add to end of array
myOtherArray[myOtherArray.length] = "new stuff";
// or you can use push()
myOtherArray.push("new stuff");
// you can remove this last item by using pop()
myOtherArray.pop();
// shift and unshift will do the same for the begging of the Array
myOtherArray.shift();
myOtherArray.unshift(1,2);
// this will add 1 and 2 to beginning of array and return new length
myOtherArray.splice(2, 1);
// this will remove and return the third item only.
// first arg is where to start and second is how many things to splice. this example is 1.
10
JAVASCRIPT
OBJECTS
// create an object
var newObject = {};
// add a property to object
newObject.newPropName = "super fly";
// or other syntax
newObject['other new prop name'] = "mildly fly";
// Now newObject.newPropName will return super fly
newObject.newPropName;
// now to delete
delete newObject.newPropName;
11
JAVASCRIPT
TYPE CHECKING
var myNumber = 1;
var myString = "some Text";
var bools = true;
var myArray = [];
var myObj = {};
var notNumber = NaN;
var nullified = null;
typeof myNumber; // returns "number"
typeof myString; // returns "string"
typeof bools; // returns "boolean"
typeof myArray; // returns "object".
// Not super helpful so must check if it has length property to see if it is an array.
typeof myArray === 'object' && myArray.hasOwnProperty('length'); // returns true
typeof myObj; // returns "object". Must do the same test as above but expect false back from check.
typeof notNumber; // returns "number". this is confusing but returns this as NaN is part of the global Number object.
// must check if isNaN()
typeof notNumber === 'number' && isNaN(notNumber); // returns true if type of is "number" and is still NaN
12
JAVASCRIPT
FUNCTIONS
var myFunction = function myFunction(arg1, arg2) {
var arg1 = (typeof arg1 !== 'undefined') ? arg1 : "default argument one";
var arg2 = (typeof arg2 !== 'undefined') ? arg2 : "default argument two";
console.log(arg1 + " & " + arg2);
};
myFunction("string", 10);
function multiply(num1, num2) {
var result = num1 * num2;
return result;
}
var result = multiply(3, 10);
13
JAVASCRIPT
EVENTS
var newElement = document.getElementsByTagName('h1');
newElement.onclick = function() {
console.log('clicked');
};
newElement.addEventListener("focus", function(event) {
console.log('focused');
}, false);
newElement.removeEventListener("focus", function(event) {
console.log('focused');
}, false);
window.onload = function() {
console.log("Im loaded");
};
14
JAVASCRIPT
TIMERS
function simpleMessage() {
alert("This is just a simple alert");
}
// set time out
window.setTimeout(simpleMessage, 5000);
// if you wanted to clear the timer.
var timer = window.setTimeout(simpleMessage, 5000);
window.clearTimeout(timer);
// set interval. will repeat every 5000ms
window.setInterval(simpleMessage, 5000);
// if you wanted to clear the intervals.
var intervalHandler = window.setInterval(simpleMessage, 5000);
window.clearInterval(intervalHandle);
15
JAVASCRIPT
ACCESSING DOM ELEMENTS
16
// Returns a reference to the element by its ID.
document.getElementById(id);
// Returns an array-like object of all child elements which have all of the given class
names.
document.getElementsByClassName(names);
// Returns an HTMLCollection of elements with the given tag name.
document.getElementsByTagName(name);
// Returns the first element within the document that matches the specified group of
selectors.
document.querySelector(selectors);
// Returns a list of the elements within the document (using depth-first pre-order
traversal of the document's nodes)
// that match the specified group of selectors.
document.querySelectorAll(selectors);
JAVASCRIPT
GRAB CHILDREN/PARENT NODE(S)
17
// Get child nodes
var stored = document.getElementById('heading');
var children = stored.childNodes;
console.log(children);
// Get parent node
var parental = children.parentNode;
JAVASCRIPT
CREATE NEW DOM ELEMENTS
18
// create new elments
var newHeading = document.createElement('h1');
var newParagraph = document.createElement('p');
// create text nodes for new elements
var h1Text= document.createTextNode("This is the header text!");
var paraText= document.createTextNode("This is the Paragraph text!");
// attach new text nodes to new elements
newHeading.appendChild(h1Text);
newParagraph.appendChild(paraText);
// elements are now created and ready to be added to the DOM.
JAVASCRIPT
ADD ELEMENTS TO THE DOM
19
// grab element on page you want to add stuff to
var firstHeading = document.getElementById('firstHeading');
// add both new elements to the page as children to the element we stored in
firstHeading.
firstHeading.appendChild(newHeading);
firstHeading.appendChild(newParagraph);
// can also insert before like so
// get parent node of firstHeading
var parent = firstHeading.parentNode;
// insert newHeading before FirstHeading
parent.insertBefore(newHeading, firstHeading);
JAVASCRIPT
WORKING WITH ATTRIBUTES
20
var element = document.getElementById('mainTitle'),
attribute = 'title';
element.getAttribute(attribute);
// Returns the specified attribute value of an element node.
element.hasAttribute(attribute);
// Returns true if an element has the specified attribute, otherwise false.
element.setAttribute(attribute);
// Sets or changes the specified attribute, to the specified value.
element.removeAttribute(attribute);
// Removes a specified attribute from an element.
JAVASCRIPT
WORKING WITH CSS & CLASSES
21
var element = document.getElementById('mainTitle');
element.style.color = "green";
element.style.borderColor = "blue";
element.style.borderWidth = "2px";
// add class
if (element.classList) {
element.classList.add(className);
} else {
element.className += ' ' + className;
}
// remove class
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|b)' + className.split('
').join('|') + '(b|$)', 'gi'), ' ');
}
JAVASCRIPT
AJAX
22
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.burningkeyboards.com/v1/user');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
console.log(userInfo.id);
} else {
console.log("API error");
}
};
xhr.send(JSON.stringify({
name: 'Denis Ristic',
age: 30
}));
JAVASCRIPT
JAVASCRIPT OOP
23
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
this.bio = function() {
console.log(this.name.first + ' ' + this.name.last);
if (this.gender == "male") {
console.log('He is ' + this.age + ' years old.');
console.log('He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
} else {
console.log('She is ' + this.age + ' years old.');
console.log('She likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
}
};
this.greeting = function() {
console.log('Hi! I'm ' + this.name.first + '.');
};
}
JAVASCRIPT
JAVASCRIPT RESOURCES
▸ Mozilla Developers Network
▸ https://developer.mozilla.org/en-US/docs/Web/JavaScript
▸ w3schools Java Script
▸ https://www.w3schools.com/js/default.asp
▸ JavaScript Style Guide
▸ Google: https://google.github.io/styleguide/jsguide.html
▸ Airbnb: https://github.com/airbnb/javascript/blob/master/README.md
▸ JavaScript validation (linter)
▸ http://www.jslint.com/
▸ http://jshint.com/
24
JAVASCRIPT
JAVASCRIPT RESOURCES
▸ Chrome DevTools
▸ https://developers.google.com/web/tools/chrome-devtools/
▸ Chrome DevTools Masterclass
▸ https://www.youtube.com/watch?v=KykP5Z5E4kA
▸ Chrome DevTools JavaScript debugging
▸ https://developers.google.com/web/tools/chrome-devtools/javascript/
▸ JavaScript Perormance Playground
▸ https://jsperf.com/
25

Mais conteúdo relacionado

Mais procurados

Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonMLRiza Fahmi
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code OrganizationRebecca Murphey
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End DevsRebecca Murphey
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 

Mais procurados (20)

Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Why ruby
Why rubyWhy ruby
Why ruby
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 

Semelhante a 05 JavaScript #burningkeyboards

10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxssuser454af01
 

Semelhante a 05 JavaScript #burningkeyboards (20)

Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Java script
Java scriptJava script
Java script
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 

Mais de Denis Ristic

Magento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRMagento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRDenis Ristic
 
Continuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzContinuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzDenis Ristic
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboardsDenis Ristic
 
24 Scrum #burningkeyboards
24 Scrum #burningkeyboards24 Scrum #burningkeyboards
24 Scrum #burningkeyboardsDenis Ristic
 
23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboardsDenis Ristic
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboardsDenis Ristic
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboardsDenis Ristic
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboardsDenis Ristic
 
19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboardsDenis Ristic
 
18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboardsDenis Ristic
 
17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboardsDenis Ristic
 
16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboardsDenis Ristic
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboardsDenis Ristic
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboardsDenis Ristic
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboardsDenis Ristic
 
12 Composer #burningkeyboards
12 Composer #burningkeyboards12 Composer #burningkeyboards
12 Composer #burningkeyboardsDenis Ristic
 
11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboardsDenis Ristic
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboardsDenis Ristic
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 

Mais de Denis Ristic (20)

Magento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRMagento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HR
 
Continuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzContinuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVz
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards
 
24 Scrum #burningkeyboards
24 Scrum #burningkeyboards24 Scrum #burningkeyboards
24 Scrum #burningkeyboards
 
23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards
 
19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards
 
18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboards
 
17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards
 
16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards
 
12 Composer #burningkeyboards
12 Composer #burningkeyboards12 Composer #burningkeyboards
12 Composer #burningkeyboards
 
11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 

Último

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

05 JavaScript #burningkeyboards

  • 2. JAVASCRIPT INTRO ▸ JavaScript is a programming language used to make web pages interactive. ▸ In our case it runs on your visitor's computer (browser). ▸ JavaScript support is built right into all the major web browsers. ▸ JavaScript is an interpreted language, so no special program is required to create usable code. ▸ JavaScript is used in HTML by inserting a <script> tag: ▸ JavaScript code is written inside <script> tag (bad practice) ▸ .js files are linked using <script src=“link/file.js”> 2
  • 3. JAVASCRIPT DOCUMENT OBJECT MODEL ▸ The HTML DOM is a standard object model and programming interface for HTML ▸ It defines: ▸ The HTML elements as objects ▸ The properties of all HTML elements ▸ The methods to access all HTML elements ▸ The events for all HTML elements 3
  • 4. JAVASCRIPT COMMON DOM EVENTS ▸ Here is a list of some common HTML events: ▸ onchangeAn HTML element has been changed ▸ onclick The user clicks an HTML element ▸ onmouseover The user moves the mouse over an HTML element ▸ onmouseout The user moves the mouse away from an HTML element ▸ onkeydown The user pushes a keyboard key ▸ onload The browser has finished loading the page ▸ onfocus An element has received focus ▸ onblur An element has lost focus 4
  • 5. JAVASCRIPT CONSOLE ▸ The Console object provides access to the browser's debugging console. ▸ Docs: ▸ https://developer.mozilla.org/en-US/docs/Web/API/Console ▸ https://developers.google.com/web/tools/chrome-devtools/ console/ ▸ How to open Console in Google Chrome: ▸ Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac). 5
  • 6. JAVASCRIPT CONSOLE ▸ Methods: ▸ console.error() ▸ console.warn() ▸ console.info() ▸ console.log() ▸ console.time() & console.timeEnd() & console.timeStamp() ▸ console.profile() & console.profileEnd() ▸ console.clear() ▸ console.dir() & console.dirXml() ▸ console.group() & console.groupEnd() & console.groupCollapsed() ▸ console.count() ▸ console.assert() ▸ console.trace() 6
  • 7. JAVASCRIPT VARIABLES, OPERATORS & COMMENTS var myVariable = 'BurningKeyboards'; myVariable = 'Perpetuum'; var myIntVariable = 10; var myBoolVariable = true; var myArrayVariable = [1, 'Bob', 'Steve', 10]; var myObjectVariable = document.querySelector('h1'); var add = 6 + 9; var concat = "Hello " + "world!"; var subtract = 9 - 3; var multiply = 8 * 2; var divide = 9 / 3; /* Everything in between is a comment. */ // This is a one line comment 7
  • 8. JAVASCRIPT CONDITIONALS /* Multi If, ElseIf, Else statements */ var a = 1; var b = 2; var c = 3; if( a > b ) { console.log('the if is true!'); } else if(a > c) { console.log('OK, THIS if is True!'); } else { console.log('None of these were true'); } // Ternary operators. same as if else var a = 1; var b = 2; a === b ? console.log('The statement is true') : console.log('The statement is false'); // switch statements var a = 4; switch (a) { case "Oranges": console.log("Orange? really?"); break; case 1: console.log("a is equal to 1."); break; default: console.log("I run if no one else is true."); } 8
  • 9. JAVASCRIPT LOOPS // while loop var i = 0; while( i < 10 ) { console.log(i); i += 1; } // do while loop var i = 0; do { console.log(i); i += 1; } while ( i < 10 ) // for loop for ( var i = 0; i < 10; i++ ) { console.log(i); } // for in statements var obj = {a:1, b:2, c:3}; for ( var prop in obj ) { // check if property is inherited or not if(obj.hasOwnProperty(prop)) { console.log("obj." + prop + " = " + obj[prop]); } } 9
  • 10. JAVASCRIPT ARRAYS // create an empty array var myArray = []; // create array with items. Can store any type var myOtherArray = [myArray, true, "A random string"]; // call specific value in an array myOtherArray[0]; // change value for this item myOtherArray[0] = false; // add to end of array myOtherArray[myOtherArray.length] = "new stuff"; // or you can use push() myOtherArray.push("new stuff"); // you can remove this last item by using pop() myOtherArray.pop(); // shift and unshift will do the same for the begging of the Array myOtherArray.shift(); myOtherArray.unshift(1,2); // this will add 1 and 2 to beginning of array and return new length myOtherArray.splice(2, 1); // this will remove and return the third item only. // first arg is where to start and second is how many things to splice. this example is 1. 10
  • 11. JAVASCRIPT OBJECTS // create an object var newObject = {}; // add a property to object newObject.newPropName = "super fly"; // or other syntax newObject['other new prop name'] = "mildly fly"; // Now newObject.newPropName will return super fly newObject.newPropName; // now to delete delete newObject.newPropName; 11
  • 12. JAVASCRIPT TYPE CHECKING var myNumber = 1; var myString = "some Text"; var bools = true; var myArray = []; var myObj = {}; var notNumber = NaN; var nullified = null; typeof myNumber; // returns "number" typeof myString; // returns "string" typeof bools; // returns "boolean" typeof myArray; // returns "object". // Not super helpful so must check if it has length property to see if it is an array. typeof myArray === 'object' && myArray.hasOwnProperty('length'); // returns true typeof myObj; // returns "object". Must do the same test as above but expect false back from check. typeof notNumber; // returns "number". this is confusing but returns this as NaN is part of the global Number object. // must check if isNaN() typeof notNumber === 'number' && isNaN(notNumber); // returns true if type of is "number" and is still NaN 12
  • 13. JAVASCRIPT FUNCTIONS var myFunction = function myFunction(arg1, arg2) { var arg1 = (typeof arg1 !== 'undefined') ? arg1 : "default argument one"; var arg2 = (typeof arg2 !== 'undefined') ? arg2 : "default argument two"; console.log(arg1 + " & " + arg2); }; myFunction("string", 10); function multiply(num1, num2) { var result = num1 * num2; return result; } var result = multiply(3, 10); 13
  • 14. JAVASCRIPT EVENTS var newElement = document.getElementsByTagName('h1'); newElement.onclick = function() { console.log('clicked'); }; newElement.addEventListener("focus", function(event) { console.log('focused'); }, false); newElement.removeEventListener("focus", function(event) { console.log('focused'); }, false); window.onload = function() { console.log("Im loaded"); }; 14
  • 15. JAVASCRIPT TIMERS function simpleMessage() { alert("This is just a simple alert"); } // set time out window.setTimeout(simpleMessage, 5000); // if you wanted to clear the timer. var timer = window.setTimeout(simpleMessage, 5000); window.clearTimeout(timer); // set interval. will repeat every 5000ms window.setInterval(simpleMessage, 5000); // if you wanted to clear the intervals. var intervalHandler = window.setInterval(simpleMessage, 5000); window.clearInterval(intervalHandle); 15
  • 16. JAVASCRIPT ACCESSING DOM ELEMENTS 16 // Returns a reference to the element by its ID. document.getElementById(id); // Returns an array-like object of all child elements which have all of the given class names. document.getElementsByClassName(names); // Returns an HTMLCollection of elements with the given tag name. document.getElementsByTagName(name); // Returns the first element within the document that matches the specified group of selectors. document.querySelector(selectors); // Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) // that match the specified group of selectors. document.querySelectorAll(selectors);
  • 17. JAVASCRIPT GRAB CHILDREN/PARENT NODE(S) 17 // Get child nodes var stored = document.getElementById('heading'); var children = stored.childNodes; console.log(children); // Get parent node var parental = children.parentNode;
  • 18. JAVASCRIPT CREATE NEW DOM ELEMENTS 18 // create new elments var newHeading = document.createElement('h1'); var newParagraph = document.createElement('p'); // create text nodes for new elements var h1Text= document.createTextNode("This is the header text!"); var paraText= document.createTextNode("This is the Paragraph text!"); // attach new text nodes to new elements newHeading.appendChild(h1Text); newParagraph.appendChild(paraText); // elements are now created and ready to be added to the DOM.
  • 19. JAVASCRIPT ADD ELEMENTS TO THE DOM 19 // grab element on page you want to add stuff to var firstHeading = document.getElementById('firstHeading'); // add both new elements to the page as children to the element we stored in firstHeading. firstHeading.appendChild(newHeading); firstHeading.appendChild(newParagraph); // can also insert before like so // get parent node of firstHeading var parent = firstHeading.parentNode; // insert newHeading before FirstHeading parent.insertBefore(newHeading, firstHeading);
  • 20. JAVASCRIPT WORKING WITH ATTRIBUTES 20 var element = document.getElementById('mainTitle'), attribute = 'title'; element.getAttribute(attribute); // Returns the specified attribute value of an element node. element.hasAttribute(attribute); // Returns true if an element has the specified attribute, otherwise false. element.setAttribute(attribute); // Sets or changes the specified attribute, to the specified value. element.removeAttribute(attribute); // Removes a specified attribute from an element.
  • 21. JAVASCRIPT WORKING WITH CSS & CLASSES 21 var element = document.getElementById('mainTitle'); element.style.color = "green"; element.style.borderColor = "blue"; element.style.borderWidth = "2px"; // add class if (element.classList) { element.classList.add(className); } else { element.className += ' ' + className; } // remove class if (el.classList) { el.classList.remove(className); } else { el.className = el.className.replace(new RegExp('(^|b)' + className.split(' ').join('|') + '(b|$)', 'gi'), ' '); }
  • 22. JAVASCRIPT AJAX 22 var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.burningkeyboards.com/v1/user'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { var userInfo = JSON.parse(xhr.responseText); console.log(userInfo.id); } else { console.log("API error"); } }; xhr.send(JSON.stringify({ name: 'Denis Ristic', age: 30 }));
  • 23. JAVASCRIPT JAVASCRIPT OOP 23 function Person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; this.bio = function() { console.log(this.name.first + ' ' + this.name.last); if (this.gender == "male") { console.log('He is ' + this.age + ' years old.'); console.log('He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); } else { console.log('She is ' + this.age + ' years old.'); console.log('She likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); } }; this.greeting = function() { console.log('Hi! I'm ' + this.name.first + '.'); }; }
  • 24. JAVASCRIPT JAVASCRIPT RESOURCES ▸ Mozilla Developers Network ▸ https://developer.mozilla.org/en-US/docs/Web/JavaScript ▸ w3schools Java Script ▸ https://www.w3schools.com/js/default.asp ▸ JavaScript Style Guide ▸ Google: https://google.github.io/styleguide/jsguide.html ▸ Airbnb: https://github.com/airbnb/javascript/blob/master/README.md ▸ JavaScript validation (linter) ▸ http://www.jslint.com/ ▸ http://jshint.com/ 24
  • 25. JAVASCRIPT JAVASCRIPT RESOURCES ▸ Chrome DevTools ▸ https://developers.google.com/web/tools/chrome-devtools/ ▸ Chrome DevTools Masterclass ▸ https://www.youtube.com/watch?v=KykP5Z5E4kA ▸ Chrome DevTools JavaScript debugging ▸ https://developers.google.com/web/tools/chrome-devtools/javascript/ ▸ JavaScript Perormance Playground ▸ https://jsperf.com/ 25