SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 

Kürzlich hochgeladen (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 

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