Comments
to make comments in JS use:
// Comment goes here
Usage: comment is one line only
or
/* commented out code goes here */
Usage: comment is multiple lines, encased within the /* */
Variables
Variable Types
var - Global Scope / Function Scope
Example:
var $name = 'Anthony Maximus';
const - Constant Variable cannot be redeclared
Example:
const insta = 'https://www.instagram.com/professor_maximusxo';
let - Can be redeclared / changed
Example:
let youtube = 'https://www.youtube.com/@professormaximus9556';
Differences
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Reassignable | ✅ Yes | ✅ Yes | ❌ No |
| Redeclarable | ✅ Yes | ❌ No | ❌ No |
| Hoisted | ✅ Yes (initialized as undefined) |
✅ Yes (not initialized) | ✅ Yes (not initialized) |
You can store anything in a variable
This box is stored in a variable
Look in cheatsheet.js this box's variable name is: boxvariable and the margin on it is generated via JS.
const boxvariable = document.getElementById('var-box');
Output
When we store or take data, we may want to output that data. There are various ways to do so in JS.
Window Alert
Displays an alert window
window.alert()
window.alert('Welcome to the JS Cheat Sheet!');
Console Log
Outputs data to the developer tools console
console.log()
console.log($name, insta, youtube, website);
InnerHTML
Outputs structure and data to the HTML
.innerHTML
document.getElementById('id_name').InnerHTML = 'Content goes here';
InnerText
Outputs data to the HTML
.innerText
document.getElementById('id_name').InnerText = 'Content goes here';
Document Write
document.write();
Document Write will erase all the existing HTML and rewrite it with what you put in it
Document Print
Print the page or save it as a PDF
onClick"window.print()"
Methods
Methods are the ways in which we can do things
We want to tartet an element in the HTML and manipulate it right? We have to do this some how. A method is how!
.getElementByID - The method in this case in which we will pluck the element up is by way of its ID given to it in the HTML.
document.getElementById('someId1');
Here we target an element with the ID of 'someId1' but we didnt do anything to it.
document.getElementById('someId2').style.backgroundColor = 'blue';
Here we targeted an element with the ID of 'someId2' and then changed the backgroundColor on it.
Dom Manipulation
Editing styles of things using JS
One of the many use cases of JS in front end design is manipulation of the DOM (Document Object Model) this can be dont in conjunction with a transition property placed on the element in the css to make the change happen over time.
Box 1
In the case of #box1 we just select it and change the background color. There is no transition and no event handler. Just plain ol static change here.
document.getElementById('box1').style.backgroundColor = 'red';
Box 2
In the case of #box2 there is a transition property on it in the CSS. So the change happens over time. But there is no event handler so it just runs the change on page load. Reload the page here to see it!
document.getElementById('box2').style.width = '97%';
Functions
How to make a function
A function is a block of code that does something, it can be executed in various ways when different events happen, like when something is clicked on for example.
function function_name() {
//code here
}
Functions and Scope
Below is a function named run_math. There is a variable within it named x. Because the variable x is inside a function, you have to use it inside the function because it is scoped to it. If you tried to use the variable outside of the function it would return an error in the console.
function run_math() {
let x = 1+1; //this is the variable
document.querySelector('.math-box').innerText = x;
}
When you click the button below it will put the sum of x in a div below it with a class if "math-box".
Event Handling
Mouse Events
Box 3 - onclick event
In this case the box will expand when it is clicked on.
function box_click() {
document.getElementById('box3').style.width = '97%';
}
Note that #box3 does not have a transform property on it in the CSS so the change is immediate!
Box 4 - ondblclick event
In this case, this function will only happen when we actually interact with the targeted element, in this case dblclick.
function box_double_click() {
document.getElementById('box4').style.width = '97%';
}
Box 5 - onmouseover event
In this case the event will happen when the mouse moves over the box.
function box_mouseover() {
document.getElementById('box5').style.width = '97%';
document.getElementById('box5').style.backgroundColor = 'skyblue';
}
Box 6 - onmouseenter event & onmouseleave event
In this case the event will happen when the mouse enters the element and again when the mouse leaves the element.
function box_mouseenter() {
document.getElementById('box6').style.width = '97%';
document.getElementById('box6').style.backgroundColor = 'skyblue';
}
function box_return() {
document.getElementById('box6').style.width = '200px';
document.getElementById('box6').style.backgroundColor = '#fff';
}
Box 7 - onmouseleave event
In this case the event will trigger when the mouse leaves the element
function box_mouseleave() {
document.getElementById('box7').style.width = '97%';
}
Box 8 - onmousedown & onmouseup
In this case the event is on mousedown (when the button is clicked).
function box_mousedown() {
document.getElementById('box8').style.transform = 'scale(2) rotate(300deg)';
document.getElementById('box8').style.backgroundColor = 'red';
}
function box_mouseup() {
document.getElementById('box8').style.transform = 'scale(1) rotate(0deg)';
document.getElementById('box8').style.backgroundColor = '#fff';
}
Key Events
Box 9 - onkeydown event
In this case the event will trigger when the user pushes a keyboard key we will also insert the element into a variable. Lets walk through it...
Below we will insert the html element with the id of 'keydownexample' into a variable, it will be easier to work with that way.
let key_down_example = document.getElementById('keydownexample');
key_down_example.addEventListener('keydown', ()=> {
key_down_example.style.backgroundColor = 'skyblue';
key_down_example.style.transform = 'scale(2) translate(35px, 0px)';
});
Compare the example we just looked at to the ones above. See the difference? Putting the element in a variable makes it easier to work with.
No need to type document.getElementById('keydownexample') over and over!
Key Down event will trigger when the user presses a key on the keyboard.
Box 10 - More efficient event handling
The better way of dealing with event handling is to use addEventListener, we can also do more advanced things like:
Below if you click 1 time it will turn red, click 2 times it will turn white.
//Insert the element into a variable
const box10 = document.getElementById('box10');
//Add the event listener when it is clicked and run the function within
box10.addEventListener('click', function() {
//Style the element
box10.style.backgroundColor = 'red';
});
//It could also look like this, using an *arrow function* '()=>' this is the superior method.
box10.addEventListener('dblclick', ()=> {
box10.style.backgroundColor = "#fff";
});
As you can see, the above example is much more efficient and faster to code. This same principle exists in many ways. Basically any time you need to handle events, it is better to use an event listener.