filmov
tv
LET'S LEARN FUNCTIONS | Simple JS Project & Javascript Training Tutorial
Показать описание
Javascript Functions
What is a function?
Functions are objects that allow us to store and reuse code
We call or ‘invoke’ a function by using its name followed by ()
Example: myFunction();
You can make your own functions
Makes your code more readable
Helps you to reuse common blocks of code
There are MANY built-in functions
Before you go writing a new function, check the docs / google to see if there is already one that does what you want
Roll your own functions
Basic Syntax
function name(arguments) {
// your code goes here
}
var name = function(arguments) {
// your code goes here
}
Example
var myFunction = function(puppy) {
// do something with puppy
}
Generates a random number between 0 & 1 (i.e. 0.001...., .79215…)
Typically we multiply this by the number we want as the maximum.
Rounds a number to the largest integer less than or equal to a given number.
.length
Not technically a function
Length is actually a property of all javascript objects. Since everything is an object, almost everything will have a length.
For strings it returns the total number of characters, for arrays it returns the number of items in the array
DOM Manipulation
Document Object Model
This is what the user sees when they visit a website.
If you’re building a web page you’ll be manipulating it a lot!
Targeting Elements
Use one of the getElementsBy:
getElementsByTagName(tag);
getElementsByClassName(class);
getElementsById(id);
Manipulating Elements
There’s a lot of ways to do this. We’ll use .innerText, but you can find many more by doing a google search
addEventListener()
There are many listeners, we’ll just be using ‘click’ to see when the user clicks an image
Listeners wait for an event to happen