fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,23 @@
---
title: Add New Properties to a JavaScript Object
---
You can add new properties to existing JavaScript objects the same way you would modify them.
There are two different syntaxes, dot notation and bracket notation. Dot notation is generally preferred for readability but properties must be a valid identifier.
Here is how using dot notation:
myDog.bark = "woof-woof";
Here is how using bracket notation:
```javascript
myObject['bark'] = "woof-woof";
```
Using bracket notation, we can utilize variables as property names:
```javascript
var dynamicProperty = "bark";
myObject[dynamicProperty] = "woof-woof";
```

View File

@ -0,0 +1,6 @@
---
title: Add Two Numbers with JavaScript
---
JavaScript uses the `+` symbol for addition. It can also be used instead of `parseInt()` but that is beyond this.
var sum = 10 + 10;

View File

@ -0,0 +1,26 @@
---
title: Build JavaScript Objects
---
Objects are useful for storing data in a structured way, and can be used to represent real world objects, like a cars or hotel to a computer.
Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties. There are two ways main to create objects: the Object Literal and the Constructor way.
Using the Object Literal way, here's how we would create sample object:
var cat = {
name: "Whiskers",
legs: 4,
tails: 1,
enemies: ["Water", "Dogs"]
};
Using the Constructor way, here's how we would create sample object:
var cat = new Object();
cat.name = "Whiskers";
cat.legs = 4;
cat.tails = 1;
cat.enemies = ["Water", "Dogs"];
In the Constructor way, we use the `new` keyword together with `Object` (with capital 'O') to create a new object instance. Afterward, we use dot notation to assign the property names and values of the object.

View File

@ -0,0 +1,20 @@
---
title: Comment Your JavaScript Code
---
Comments are a great way to leave notes to yourself and to other people who will later need to figure out what it does. Any code in it will be ignored.
Let's take a look at the two ways you can write comments in JavaScript.
* The double-slash comment will comment out the remainder of the text on the current line:
`// This is a single line comment.`
* The slash-star-star-slash comment will comment out everything between the `/*` and the `*/` characters:
```javascript
/*
This is
a multi-line comment
(comment block)
*/
```

View File

@ -0,0 +1,15 @@
---
title: Construct JavaScript Objects with Functions
---
Using constructors it is easy to create new objects using a blueprint or constructor. The declaration syntax is a little different but still easy to remember.
// Let's add the properties engines and seats to the car in the same way that the property wheels has been added below. They should both be numbers.
var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 1;
};
var myCar = new Car();
The name of a constructor function usually begins with a capital letter (unlike other functions, which tend to begin with a lowercase character). The uppercase letter is supposed to help remind developers to use the new keyword when they create an object using that function.

View File

@ -0,0 +1,8 @@
---
title: Create a JavaScript Slot Machine
---
For this we have to generate three random numbers using the formula they give us and not the general one. `Math.floor(Math.random() * (3 - 1 + 1)) + 1;`
slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;

View File

@ -0,0 +1,6 @@
---
title: Create Decimal Numbers with JavaScript
---
JavaScript number variables can have decimals.
var myDecimal = 2.8;

View File

@ -0,0 +1,87 @@
---
title: Debugging JavaScript with Browser Devtools
---
As a developer you will often want to debug code. You might have already used `console.log` in some of the challenges, which is the simplest way to debug.
In this article we will tell you some of the coolest tricks, to debug using the native debug-tools of the browsers.
## A brief insight into the FreeCodeCamp Code Editor:
Before jumping into debugging lets leak out some secret facts about that _awesome code checking engine_ at FCC.
We use a customized <a href='http://codemirror.net/mode/javascript/index.html' target='_blank' rel='nofollow'>CodeMirror</a>, as the code editor. A <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval' target='_blank' rel='nofollow'>`eval()` function</a> is used to evaluate the JavaScript code represented as a string from the editor. When `eval()` is called, browsers will natively execute your code. We will learn more why this secret is important in later sections of this article.
## Now moving on to the tricks:
## Google Chrome DevTools
Google Chrome is one of the most popular browsers with a built-in JavaScript engine called <a href='https://developers.google.com/v8/' target='_blank' rel='nofollow'>V8</a>, and offers a great toolset for developers called <a href='https://developer.chrome.com/devtools' target='_blank' rel='nofollow'>Chrome DevTools</a>. Visiting their <a href='https://developer.chrome.com/devtools/docs/javascript-debugging' target='_blank' rel='nofollow'>Complete JavaScript debugging guide</a> is highly recommended.
### 1 : Basics of DevTools
#### Launching the Chrome DevTools
Hit `F12`
. Alternatively you can press
`Ctrl` + `Shift` + `I`
on Windows and Linux or
`Cmd` + `Shift` + `I`
on Mac, or If you just love your mouse go to `Menu > More Tools > Developer Tools`.
#### Getting to know the `Sources` and the `console` tabs.
These two tabs are the perhaps going to be your best friends while debugging. The `Sources` tab can be used to visualize all the scripts that's on the webpage you are visiting. This tab has sections for the code window, file tree, call stack & watch windows, etc.
The `console` tab is where all of the log output goes. Additionally you can use the console tab's prompt to execute JavaScript code. Its kind of synonymous to the command prompt on Windows, or terminal on Linux.
_Tip : Toggle the console anytime in the DevTools using `Esc` key._
### 2 : Common Shortcuts and features
While you can visit the <a href='https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts' target='_blank' rel='nofollow'>complete list of shortcuts</a>, below are a few that are most used:
Feature Windows, Linux Mac
Search for a keyword, regex is supported. `Ctrl`+`F``Cmd`+`F`
Search and Open a file `Ctrl`+`P``Cmd`+`P`
Jump to line `Ctrl`+`G`+`:line_no``Cmd`+`G`+`:line_no`
Add a breakpoint `Ctrl`+`B`, or click on the line no.`Cmd`+`B`, or click on the line no.
Pause / resume script execution `F8` `F8`
Step over next function call `F10` `F10`
Step into next function call `F11` `F11`
### 3 : Using a Source Map for our Code
One of the coolest feature that you will love is <a href='https://developer.chrome.com/devtools/docs/javascript-debugging#breakpoints-dynamic-javascript' target='_blank' rel='nofollow'>debugging Dynamic Script</a>, on the fly, via <a href='https://developer.chrome.com/devtools/docs/javascript-debugging#source-maps' target='_blank' rel='nofollow'>Source Maps</a>.
Every script can be visualized in the Source tab of the DevTools. The source tab has all the JavaScript source files. But the code from the code editor is executed via `eval()`in a container simply called a virtual machine(VM) within the browser process.
As you might have guessed by now is that our code is actually a script that doesn't have a file name. So we don't see that in the Source tab.
> ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":sparkles:") **_Here comes the hack!_** ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":sparkles:")
We must leverage `Source Maps` to assign a name to the JavaScript from our editor. Its pretty simple:
Lets say we are on the <a href='https://www.freecodecamp.com/challenges/factorialize-a-number' target='_blank' rel='nofollow'>Factorialize</a> challenge, and our code looks like this:
function factorialize(num) {
if(num <= 1){
...
}
factorialize(5);
All we need to do is add `//# sourceURL=factorialize.js` to the top of the code, i.e the first line:
//# sourceURL=factorialize.js
function factorialize(num) {
if(num <= 1){
...
> ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":sparkles:") **_And Eureka that's it!_** ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":sparkles:")
Now open up the DevTools and search for the file name. Add break points, Debug away and enjoy!

View File

@ -0,0 +1,47 @@
---
title: Debugging Node files using CLI commands
---
## Debugging Node files using CLI commands
In this tutorial you will learn how you can debug your Node.js code on the command line. Your plain JavaScript code can be easily debugged using the DevTools of a browser. For Node, you can debug your code without ever leaving your Command Line Interface (CLI).
Let's say you have a file named as `contents.js`. You would run the file using the `node` command.
```bash
node contents.js
```
This much must be already known to you since you're writing Node.js code. Now any errors that pop up must be debugged. To run the file in debug mode append the keyword `inspect` while running the file.
```bash
node inspect contents.js
```
Now this command will open your file in debug mode. From here on, you can step through your code one line at a time by pressing the **N** key on your keyboard.
The debugger will start at the very first line. By pressing **N**, you can move the debugger to the next line. If there was an error on the first line, it would show an error instead of moving to the second line. This is very useful. If for example, there is an error on the 17th line, it will show you the error before moving forward.
There can be an error in your logic, meaning, you want a certain value to be displayed but instead it shows a different value. In that case, adding `console.log()`s might help you and with debug mode, it will become easier to identify the cause of the error.
---
Now sometimes, it happens that your source code is huge. You go into debug mode to debug your errors and you are certain that the error is from a function on line 52. But since debug mode starts at line 1, do you have no choice but to visit line 52 one by one? Absolutely not!
Simply add the keyword `debugger` before the function.
```javascript
console.log("Outside the function....everything's going smoothly");
debugger;
function doesSomething() {
//some logic
console.log("Something went wrong inside here!");
}
```
Now open the file again in debug mode and this time press **C** on your keyboard.
Pressing **N** moves the debugger to the next line and pressing **C** tells the debugger to go through the entire code in one go. That is the same as running without debug mode. *But*, your code has an addition this time. You guessed it - the `debugger` keyword. Pressing **C** would normally run the code till the end, but because of adding `debugger`, it will stop right before the function starts.
So after running your file in debug mode, pressing **C** will skip the code and stop exactly before the function at the `debugger` keyword. After that, you can start stepping through the function one line at a time till you pinpoint your error.

View File

@ -0,0 +1,29 @@
---
title: Declare JavaScript Objects as Variables
---
This has a simple format. You declare your variable and have it equal to an object in the form `{ key: value}`
var car = {
"wheels":4,
"engines":1,
"seats":5
};
You can access the object's properties using dot notation or bracket notation.
Using dot notation:
```javascript
console.log(car.wheels); // 4
```
Using bracket notation:
```javascript
console.log(car["wheels"]); // 1
```
Using dynamic bracket notation:
```javascript
var seatsProperty = "seats";
console.log(car[seatsProperty]); // 5
```

View File

@ -0,0 +1,78 @@
---
title: Declare Variables
---
# Declare Variables
JavaScript variable declarations can be sorted into three distinct components: the variable type, the variable name, and the variable value.
```js
var myName = "Rafael";
```
Let's break the above line of code into the pieces that make it up:
```js
var/const/let
```
JavaScript variables can have three declaration types: var, const, and let. Var-type variables are global, if declared outside a function they can be accessed by any JS file (or the console), and if created within a function they are accessible regardless of block scope. Let-type variables are limited in scope to their block. See the example below for the difference.
```js
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
```
Const-type variables have the same scope as let variables (block scope), but are immutable. Whatever value a const-type variable is to be assigned, must happen when the variable is declared, and JavaScript will thrown an error if the variable is changed later.
```js
const genre = "non-fiction";
console.log(genre); // "non-fiction";
genre = "fantasy"; // error
```
Now that we can determine what the variable type is, let's take a look at the name. JavaScript variable names are written in `camel case` format. An example of camel case is: `camelCase`. In the context of our example:
```js
myName
```
The name is also we'll access the variable again later:
```js
console.log(myName); // "Rafael"
```
Finally, our value:
```js
"Rafael"
```
JavaScript is dynamically typed, which means any given variable can represent any given data type at any given time. For example:
```js
var example = "This is an example";
example = [0, 1, 2, 3]
example = {test: "Result"}
example = 5
```
All those statements are perfectly valid - JavaScript variables can jump from string to array to object to integer.
### Declare object as const
As mentioned above, const variable are immutable means value assigned to such variable at the time of declaration cannot be updated but there is a point to note in case object declaration with const. Object of type const also cannot be updated once defined but properties of object cab be. For example.
```js
const Car1 = {
name: 'BMW',
model: 'X1',
color: 'black'
}
```
Here, we cannot update the object but we can update the properties by accessing through dot(.) operator as below.
```js
Car1.color = 'Red';
console.log(Car1);
O/P - {name: "BMW", model: "X1", color: "Red"}
```
If we need to to make enitre object as immutable (including properties) then we have to use freeze method.

View File

@ -0,0 +1,12 @@
---
title: Decrement a Number with JavaScript
---
You can easily decrement or decrease a variable by `1` with the `--` operator.
i--;
is the equivalent of
i = i - 1;
**Note:** The entire line becomes `i--;`, eliminating the need for the equal sign.

View File

@ -0,0 +1,39 @@
---
title: Delete Properties from a JavaScript Object
---
We can also delete properties from objects like this:
delete ourDog.bark;
The **delete operator** removes a property from an object.
## Syntax
`delete expression` where expression should evaluate to a property reference, e.g.:
delete object.property
delete object['property']
## Parameters
**object** <br/>
The name of an object, or an expression evaluating to an object.
**property** <br/>
The property to delete.
## Example
```js
var person = {name:'Jay', age:'52'};
delete person['age'];
console.log(person); //{name:'Jay'}
```
## Return value
Throws in strict mode if the property is an own non-configurable property (returns false in non-strict). Returns true in all other cases.
[Read more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)

View File

@ -0,0 +1,26 @@
---
title: Detect authentic click events
---
## Detect authentic click events
There might be a situation where you want to do some specific things only if the click event was genuinely triggered by a user and not by some script to simulate a click event.
There is a very simple solution to this problem, javascript event object provides us with a `.istrusted` property, which can be used to tell the difference.
#### Here is an example of using this method
```javascript
// Assume there is a button in the HTML
const button = document.querySelector('button');
button.addEventListener('click', (e) => {
if (e.isTrusted) {
console.log('Button clicked by a real user');
} else {
console.log('Button click simulated by a script');
}
});
button.click() // Outputs "Button click simulated by a script"
```

View File

@ -0,0 +1,6 @@
---
title: Divide One Number by Another with JavaScript
---
JavaScript uses use the `/` symbol for division.
var quotient = 66 / 33;

View File

@ -0,0 +1,20 @@
---
title: Finding a Remainder in JavaScript
---
The _remainder operator_ `%` gives the remainder of the division of two numbers.
## Example
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
## Usage
In mathematics, a number can be checked even or odd by checking the remainder of the division of the number by 2.
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
**Note** Do not confuse it with _modulus_ `%` does not work well with negative numbers.

View File

@ -0,0 +1,4 @@
---
title: Generate Random Fractions with JavaScript
---
JavaScript has a `Math.random()` function that generates a random decimal number.

View File

@ -0,0 +1,8 @@
---
title: Generate Random Whole Numbers with JavaScript
---
It's great that we can create random decimal numbers, but it's even more useful if we lot more useful to generate a random whole number.
To achieve this we can multiply the random number by ten and use the `Math.floor()` to convert the decimal number to a whole number
Math.floor(Math.random()*10)

View File

@ -0,0 +1,12 @@
---
title: Get Current Url in JavaScript
---
To get the **current URL**:
var url = window.location.href;
To get the **current path**:
var path = window.location.path;
More information about the location object and its properties can be found <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/location' target='_blank' rel='nofollow'>here</a>.

View File

@ -0,0 +1,8 @@
---
title: Give Your JavaScript Slot Machine Some Stylish Images
---
We've already set up the images for you in an array called images. We can use different indexes to grab each of these.
Here's how we would set the first slot to show a different image depending on which number its random number generates:
$($('.slot')[0]).html('<img src = "' + images[slotOne-1] + '">');

View File

@ -0,0 +1,57 @@
---
title: How to Create a Countdown Timer
---
## How to Create a Countdown Timer
### Creation
Start by building the countdownTimer function.
```javascript
function startCountdown(seconds){
var counter = seconds;
var interval = setInterval(() => {
console.log(counter);
counter--;
if(counter < 0 ){
// The code here will run when
// the timer has reached zero.
clearInterval(interval);
console.log('Ding!');
};
}, 1000);
};
```
### Execution
Now to start the timer we provide `startCountdown()` with a number value as an argument which represents the seconds to countdown.
```javascript
startCountdown(10);
// Console Output //
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// 0
// Ding!
```
### Live Example
<a href='https://codepen.io/rdev-rocks/pen/jLogxY?editors=0012' target='_blank' rel='nofollow'>Codepen - Countdown Timer</a>
### More Resources
Methods used:
* <a href='https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval' target='_blank' rel='nofollow'>setInterval()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval' target='_blank' rel='nofollow'>clearInterval()</a>

View File

@ -0,0 +1,233 @@
---
title: How to Create a Dropdown Menu with CSS and JavaScript
---
## How to Create a Dropdown Menu with CSS and JavaScript
In this tutorial you will learn how to create a simple dropdown menu with vanilla Javascript, HTML and CSS. We will walk through the HTML, CSS and Javascript code, but paying more attention to the programming, since this is a JS tutorial. We'll use just plain JS and CSS, with no frameworks or preprocessors. The only (kind-of) exception will be importing the [Font Awesome](https://fontawesome.com/) CSS file because we'll use one of its icons.
This is targeted to developers that have an average understanding of HTML, CSS and JS. I tried to make it as clean as possible, but I won't focus too much on details here. I hope you all enjoy.
## Screenshots
This is how the code result looks like:
Initial screen:
<img src="https://i.imgur.com/jrnu6mE.png" width="200px"></img>
Dropdown opened:
<img src="https://i.imgur.com/gszPtRa.png" width="200px"></img>
Dropdown with option selected:
<img src="https://i.imgur.com/TKXxZGF.png" width="200px"></img>
#### HTML:
In this section, we will discuss the implementation of the HTML code for the demo page.
To start off, let's see the `<head>` code
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dropdown Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/'-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="styles.css">
</head>
```
This is basically HTML head boilerplate, with the exception of the `link` tags loading the two CSS stylesheets we will use in this tutorial: the Font Awesome styles, and the `styles.css` file, where we will define this page's styles.
Then, there's the rest of the HTML file, the body:
```html
<body>
<div class='dropdown'>
<div class='title pointerCursor'>Select an option <i class="fa fa-angle-right"></i></div>
<div class='menu pointerCursor hide'>
<div class='option' id='option1'>Option 1</div>
<div class='option' id='option2'>Option 2</div>
<div class='option' id='option3'>Option 3</div>
<div class='option' id='option4'>Option 4</div>
</div>
</div>
<span id='result'>The result is: </span>
<script>
...
</script>
</body>
</html>
```
This section can be divided into 3 main parts:
* The `.dropdown` div, where the dropdown element's structure will be defined.
* The `#result` element, that will contain the selected option by the user, from the dropdown element.
* The script written into the `<script>` tag. Its implementation is hidden here, because its details will be explained in the last section of this tutorial.
The dropdown element is a `div` containing a `title` and `menu` elements. The former just defines what text will be presented on the element before any option is selected and the latter will define the options that will be selectable by the element.
The `result` element is there just to show you what option is currently selected.
#### Styles:
Below you can check the full css code out. As you can see it makes use of CSS3 `transition` and `transform` constructs.
Please pay attention to the `.dropdown` classes definitions. These are used to define the layout for the dropdown container component as well as its inner elements, such as the `.title` and its `.option`'s.
```css
body{
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
.hide {
max-height: 0 !important;
}
.dropdown{
border: 0.1em solid black;
width: 10em;
margin-bottom: 1em;
}
.dropdown .title{
margin: .3em .3em .3em .3em;
width: 100%;
}
.dropdown .title .fa-angle-right{
float: right;
margin-right: .7em;
transition: transform .3s;
}
.dropdown .menu{
transition: max-height .5s ease-out;
max-height: 20em;
overflow: hidden;
}
.dropdown .menu .option{
margin: .3em .3em .3em .3em;
margin-top: 0.3em;
}
.dropdown .menu .option:hover{
background: rgba(0,0,0,0.2);
}
.pointerCursor:hover{
cursor: pointer;
}
.rotate-90{
transform: rotate(90deg);
}
```
#### JavaScript:
Now we'll see how the Javascript part is implemented. We'll first go through the function definitions
and then the code that calls these functions to make the dropdown actions happen.
Basically, there are 3 actions that take place depending on what the user interaction is, as their listeners are added to the DOM elements:
1. Clicking on the dropdown element
2. Selecting one of the dropdown options
3. Changing the currently selected option
I'd like to make it clear that we are using arrow functions( `() => {}` ) and the `const` keyword, which are ES6 features. You're probably good if you're using a recent version of your browser, but keep that in mind.
#### 1. Clicking on the dropdown element
```Javascript
function toggleClass(elem,className){
if (elem.className.indexOf(className) !== -1){
elem.className = elem.className.replace(className,'');
}
else{
elem.className = elem.className.replace(/\s+/g,' ') + ' ' + className;
}
return elem;
}
function toggleDisplay(elem){
const curDisplayStyle = elem.style.display;
if (curDisplayStyle === 'none' || curDisplayStyle === ''){
elem.style.display = 'block';
}
else{
elem.style.display = 'none';
}
}
function toggleMenuDisplay(e){
const dropdown = e.currentTarget.parentNode;
const menu = dropdown.querySelector('.menu');
const icon = dropdown.querySelector('.fa-angle-right');
toggleClass(menu,'hide');
toggleClass(icon,'rotate-90');
}
```
When the dropdown element is clicked, it opens(if it is closed) or closes(if it is opened). This happens by binding `toggleMenuDisplay` to the click event listener on the dropdown element. This function toggles the display of its `menu` element by the use of the `toggleDisplay` and `toggleClass` functions.
#### 2. Selecting one of the dropdown options
```Javascript
function handleOptionSelected(e){
toggleClass(e.target.parentNode, 'hide');
const id = e.target.id;
const newValue = e.target.textContent + ' ';
const titleElem = document.querySelector('.dropdown .title');
const icon = document.querySelector('.dropdown .title .fa');
titleElem.textContent = newValue;
titleElem.appendChild(icon);
//trigger custom event
document.querySelector('.dropdown .title').dispatchEvent(new Event('change'));
//setTimeout is used so transition is properly shown
setTimeout(() => toggleClass(icon,'rotate-90',0));
}
```
#### 3. Changing the currently selected option
```Javascript
function handleTitleChange(e){
const result = document.getElementById('result');
result.innerHTML = 'The result is: ' + e.target.textContent;
}
```
The function `handleTitleChange` is bound to the custom `change` event on the `.title` element, to change the `#result` element content whenever the title element changes. This event's triggering is done on the previous section.
#### Main code
```Javascript
//get elements
const dropdownTitle = document.querySelector('.dropdown .title');
const dropdownOptions = document.querySelectorAll('.dropdown .option');
//bind listeners to these elements
dropdownTitle.addEventListener('click', toggleMenuDisplay);
dropdownOptions.forEach(option => option.addEventListener('click',handleOptionSelected));
document.querySelector('.dropdown .title').addEventListener('change',handleTitleChange);
```
In the main section there's just some simple code to get the dropdown's title and options elements to bind to them the events discussed on the last section.
## Demo
This application's full code and demo can be found [here](https://codepen.io/GCrispino/pen/EEXmYd).
## More Information
* [ES6 introduction](https://guide.freecodecamp.org/javascript/es6)
* [Arrow functions](https://guide.freecodecamp.org/javascript/es6/arrow_functions/)
* [Let and Const](https://guide.freecodecamp.org/javascript/es6/let_and_const/)

View File

@ -0,0 +1,571 @@
---
title: How to Create a Lightbox
---
## How to Create a Lightbox
### Introduction
A lightbox is a combination of two components, a <a href='https://en.wikipedia.org/wiki/Modal_window' target='_blank' rel='nofollow'>modal</a> and a slide show. Here you will construct a simple lightbox using `HTML`, `CSS` and `JavaScript`.
The lightbox will be contained in the modal, which will be triggered by some `JavaScript`, from <a href='https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers' target='_blank' rel='nofollow'>event handlers</a> in the `HTML` markup.
You will build styles which will provide state with `CSS` and behavior with `JavaScript`. You will also find a reference list of the methods you use and other useful tid-bits that are related to this tutorial, at the bottom.
#### Our Images
The images we will be using are being supplied by <a href='https://www.pexels.com/' target='_blank' rel='nofollow'>Pexels</a>,
a free stock photo gallery that allows you to provide high quality images to their projects fast, free and usually with no attributions needed.
#### Just Show Me The Code!
A live example can be found <a href='https://codepen.io/rdev-rocks/pen/KXNzvo' target='_blank' rel='nofollow'>here - CodePen/Lightbox</a> and a full draft of the code is near the bottom.
### Step 1. The Markup
The markup, or `HTML`, provides the structure for the lightbox.
```html
<!-- Here is your access point for your user, a preview of the images you wish to display.
You use the onclick="" event handler to execute the methods you will define in the
JavaScript near the bottom -->
<div class="row">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" onclick="openLightbox();toSlide(1)" class="hover-shadow preview" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" onclick="openLightbox();toSlide(2)" class="hover-shadow preview" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" onclick="openLightbox();toSlide(3)" class="hover-shadow preview" alt="Toy car in the city." />
</div>
</div>
<!-- This is your lightbox, it is contained in a modal. Here you provide all the images,
controls, and another set of preview images as the dots. Dots show your user which
image is currently active. Note that you use entities (e.g. &times;), more info on
them at the bottom. -->
<div id="Lightbox" class="modal">
<span class="close pointer" onclick="closeLightbox()">&times;</span>
<div class="modal-content">
<div class="slide">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="image-slide" alt="Toy car on the road." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="image-slide" alt="Toy car exploring offroad." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="image-slide" alt="Toy car in the city." />
</div>
<a class="previous" onclick="changeSlide(-1)">&#10094;</a>
<a class="next" onclick="changeSlide(1)">&#10095;</a>
<div class="dots">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="modal-preview hover-shadow" onclick="toSlide(1)" alt="Toy car on the road" />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="modal-preview hover-shadow" onclick="toSlide(2)" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="modal-preview hover-shadow" onclick="toSlide(3)" alt="Toy car in the city." />
</div>
</div>
</div>
</div>
```
### Step 2. Style with CSS
The `CSS` provides you with different states for your lightbox. Things like visibility, positioning, and hover effects.
Your style sheet should look like this:
```css
/* Here you provide a best practice's "reset", read more about it at the bottom! :) */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
/* You define the style of our previews here, you are using flex to display the images
"responsively". */
.preview {
width: 100%;
}
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.row > .col {
padding: 0 8px;
}
.col {
float: left;
width: 25%;
}
/* Now you want to define what the lightbox will look like. Note that you have the display
as none. You don't want it to show until the user clicks on one of the previews.
You will change this display property with JavaScript below. */
.modal {
display: none;
position: fixed;
z-index: 1;
padding: 10px 62px 0px 62px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
.modal-content {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
margin: auto;
padding: 0 0 0 0;
width: 80%;
max-width: 1200px;
}
/* Same with your slides, you set the display to none, because you want to choose which
one is shown at a time. */
.slide {
display: none;
}
.image-slide {
width: 100%;
}
.modal-preview {
width: 100%;
}
.dots {
display: flex;
flex-direction: row;
justify-content: space-between;
}
/* You want the previews a little transparent to show that they are "inactive".
You then add an .active or :hover class to animate the selections for your user when
they interact with your controls and clickable content.
*/
img.preview, img.modal-preview {
opacity: 0.6;
}
img.active,
.preview:hover,
.modal-preview:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s;
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.previous,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.previous:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
```
### Step 3. JavaScript
Now to business! Your JavaScript should look like this:
```javascript
// Initialize here and run showSlide() to give your lightbox a default state.
let slideIndex = 1;
showSlide(slideIndex);
// You are providing the functionality for your clickable content, which is
// your previews, dots, controls and the close button.
function openLightbox() {
document.getElementById('Lightbox').style.display = 'block';
}
function closeLightbox() {
document.getElementById('Lightbox').style.display = 'none';
};
// Note that you are assigning new values here to our slidIndex.
function changeSlide(n) {
showSlide(slideIndex += n);
};
function toSlide(n) {
showSlide(slideIndex = n);
};
// This is your logic for the light box. It will decide which slide to show
// and which dot is active.
function showSlide(n) {
const slides = document.getElementsByClassName('slide');
let modalPreviews = document.getElementsByClassName('modal-preview');
if (n > slides.length) {
slideIndex = 1;
};
if (n < 1) {
slideIndex = slides.length;
};
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
};
for (let i = 0; i < modalPreviews.length; i++) {
modalPreviews[i].className = modalPreviews[i].className.replace(' active', '');
};
slides[slideIndex - 1].style.display = 'block';
modalPreviews[slideIndex - 1].className += ' active';
};
```
And thats it! Now put all the code together. You should now have a functional lightbox.
### All The Code
```html
<body>
<style>
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
.preview {
width: 100%;
}
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.row > .col {
padding: 0 8px;
}
.col {
float: left;
width: 25%;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding: 10px 62px 0px 62px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
.modal-content {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
margin: auto;
padding: 0 0 0 0;
width: 80%;
max-width: 1200px;
}
.slide {
display: none;
}
.image-slide {
width: 100%;
}
.modal-preview {
width: 100%;
}
.dots {
display: flex;
flex-direction: row;
justify-content: space-between;
}
img.preview, img.modal-preview {
opacity: 0.6;
}
img.active,
.preview:hover,
.modal-preview:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s;
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.previous,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.previous:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
</style>
<div class="row">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" onclick="openLightbox();toSlide(1)" class="hover-shadow preview" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" onclick="openLightbox();toSlide(2)" class="hover-shadow preview" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" onclick="openLightbox();toSlide(3)" class="hover-shadow preview" alt="Toy car in the city" />
</div>
</div>
<div id="Lightbox" class="modal">
<span class="close pointer" onclick="closeLightbox()">&times;</span>
<div class="modal-content">
<div class="slide">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="image-slide" alt="Toy car on the road." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="image-slide" alt="Toy car exploring offroad." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="image-slide" alt="Toy car in the city." />
</div>
<a class="previous" onclick="changeSlide(-1)">&#10094;</a>
<a class="next" onclick="changeSlide(1)">&#10095;</a>
<div class="dots">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="modal-preview hover-shadow" onclick="toSlide(1)" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="modal-preview hover-shadow" onclick="toSlide(2)" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="modal-preview hover-shadow" onclick="toSlide(3)" alt="Toy car in the city" />
</div>
</div>
</div>
</div>
<script>
let slideIndex = 1;
showSlide(slideIndex);
function openLightbox() {
document.getElementById('Lightbox').style.display = 'block';
};
function closeLightbox() {
document.getElementById('Lightbox').style.display = 'none';
};
function changeSlide(n) {
showSlide(slideIndex += n);
};
function toSlide(n) {
showSlide(slideIndex = n);
};
function showSlide(n) {
const slides = document.getElementsByClassName('slide');
let modalPreviews = document.getElementsByClassName('modal-preview');
if (n > slides.length) {
slideIndex = 1;
};
if (n < 1) {
slideIndex = slides.length;
};
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
};
for (let i = 0; i < modalPreviews.length; i++) {
modalPreviews[i].className = modalPreviews[i].className.replace(' active', '');
};
slides[slideIndex - 1].style.display = 'block';
modalPreviews[slideIndex - 1].className += ' active';
};
</script>
</body>
```
### More Information:
---
#### HTML
<a href='https://en.wikipedia.org/wiki/Modal_window' target='_blank' rel='nofollow'>Modal</a> - A popup window
<a href='https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers' target='_blank' rel='nofollow'>Event Handlers</a> - HTML properties that listen for user events.
<a href='https://developer.mozilla.org/en-US/docs/Glossary/Entity' target='_blank' rel='nofollow'>Entity</a> - A string that represents a reserved charactor in HTML.
#### CSS
<a href='https://css-tricks.com/box-sizing/' target='_blank' rel='nofollow'>box-sizing:</a> - A CSS3 property that controls the way the browser renders content based on height and width.
<a href='https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox' target='_blank' rel='nofollow'>Flex-box</a> - A new technology that helps with positioning HTML content in a responsive mannor.
<a href='https://developer.mozilla.org/en-US/docs/Web/CSS/:hover' target='_blank' rel='nofollow'>:hover</a> - A pseudo-selector that gets triggered when a user hovers over an element when this class is assigned to it.
#### JavaScript
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let' target='_blank' rel='nofollow'>let</a> A block-scope variable.
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const' target='_blank' rel='nofollow'>const</a> A block-scope constant.
<a href='https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById' target='_blank' rel='nofollow'>getElementById()</a> - A document method that returns a reference to an HTML element.
<a href='https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName' target='_blank' rel='nofollow'>getElementsByClassName()</a> - A document method that returns an array of references to the html that have matching classes.
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators' target='_blank' rel='nofollow'>+=</a> - an assignment operator which will add numbers or concatenate strings.
#### Resources:
<a href='https://codepen.io/rdev-rocks/pen/KXNzvo?editors=1111' target='_blank' rel='nofollow'>Live Example</a> - A CodePen that demos the above code.
<a href='https://codepen.io/enxaneta/full/adLPwv' target='_blank' rel='nofollow'>Interactive Flex-Box</a> - An interactive CodePen that shows flex-box behavior.
<a href='https://www.pexels.com/' target='_blank' rel='nofollow'>Pexels</a> - A free stock photo gallery.
<a href='https://developer.mozilla.org/en-US/' target='_blank' rel='nofollow'>MDN</a> - A great place for information about web stuff.
<a href='https://www.w3schools.com/howto/howto_js_lightbox.asp' target='_blank' rel='nofollow'>W3School - Lightbox</a> - This code was inspired from here. Thanks W3Schools!

View File

@ -0,0 +1,89 @@
---
title: How to Create a Slideshow
---
## How to Create a Slideshow
A Web slideshow is a sequence of images or text that consist in show one element of this sequence in a time interval.
For this tutorial you can create a slideshow following the next steps:
### Write a markup.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Slideshow</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="slideshow-example" data-component="slideshow">
<div role="list">
<div class="slide">
<img src="" alt="">
</div>
<div class="slide">
<img src="" alt="">
</div>
<div class="slide">
<img src="" alt="">
</div>
</div>
</div>
<script src="slideshow.js"></script>
</body>
</html>
```
### Write styles to hide slides and show only one slide.
For hide the slides you have to give them a default style and only show one slide if this is active or you want to show it.
```css
[data-component="slideshow"] .slide {
display: none;
}
[data-component="slideshow"] .slide.active {
display: block;
}
```
### Change the slides in a time interval.
The first step to change the slides to show, is select the slide wrapper(s) and then its slides.
When you selected the slides you have to go over each slide and add or remove an active class depending on the slide that you want to show, and then just repeat the process in a time interval.
Keep it in mind when you remove a active class to a slide, you are hidden it because the styles defined in the previous step. But when you add an active class to the slide, you are overwritring the style ``display:none to display:block`` , so the slide will show to the users.
```js
var slideshows = document.querySelectorAll('[data-component="slideshow"]');
// Apply to all slideshows that you define with the markup wrote
slideshows.forEach(initSlideShow);
function initSlideShow(slideshow) {
var slides = document.querySelectorAll(`#${slideshow.id} [role="list"] .slide`); // Get an array of slides
var index = 0, time = 5000;
slides[index].classList.add('active');
setInterval( () => {
slides[index].classList.remove('active');
//Go over each slide incrementing the index
index++;
// If you go over all slides, restart the index to show the first slide and start again
if (index === slides.length) index = 0;
slides[index].classList.add('active');
}, time);
}
```
#### [Codepen example following this tutorial](https://codepen.io/AndresUris/pen/rGXpvE)

View File

@ -0,0 +1,15 @@
---
title: How to Create a Top Navigation Bar
---
## How to Create a Top Navigation Bar
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-a-top-navigation-bar/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,15 @@
---
title: How to Create an Accordion
---
## How to Create an Accordion
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-an-accordion/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,98 @@
---
title: How to Create Popups
---
## How to Create Popups
Popup is a window that pops up (appears) when you select an option with a mouse or press a special function key.
In this example , the popup will appear when you click on a button and will stay on the screen until you press X option.
We will construct the popup using ```HTML``` , ```CSS``` and ```JavaScript```
### Step 1 HTML
The HTML provides the structure for the popup
```html
<!-- div class="container" will contain the button that will open the popup when I click on it, and the popup window that will appear -->
<div class="container">
<button id="Btn">Open The PopUp</button>
<div class="popup_main_div">
<p class="text">Popup with JavaScript</p>
<div class="close_popup"><p>X</p></div>
</div>
</div>
```
### Step 2 CSS
We will choose our own style for the popup window. Notice: the popup div should be hidden at first, so in the style I will select display: none;
```css
.popup_main_div{
position: fixed;
width: 800px;
height: 400px;
border: 2px solid black;
border-radius: 5px;
background-color: #fff;
left: 50%;
margin-left: -400px;
top: 50%;
margin-top: -250px;
display: none;
}
.close_popup{
position: absolute;
width: 25px;
height: 25px;
border-radius: 25px;
border: 2px solid black;
text-align: center;
right: 5px;
top: 5px;
cursor: pointer;
}
.close_popup p{
margin-top: 5px;
font-weight: 400;
}
.text{
text-align: center;
font-size: 30px;
font-weight: 400;
margin-top: 22%;
}
#Btn{
position: absolute;
left: 50%;
top:20%;
}
```
### Step 3 JavaScript
```js
// First of all I will initialize my variables
// Select the elements that we will use from the DOM
// I wiil add en event in the button which will trigger a function that will change the popup's display style from none to block
const Btn=document.getElementById("Btn")
const PopupDiv = document.querySelector(".popup_main_div")
const ClosePopup = document.querySelector(".close_popup")
Btn.addEventListener('click',function(){
PopupDiv.style.display="block"
})
ClosePopup.addEventListener('click',function(){
PopupDiv.style.display="none"
})
```
Live code in : [Codepen.io](https://codepen.io/voula12/pen/qyyNeK)

View File

@ -0,0 +1,15 @@
---
title: How to Create Tabs
---
## How to Create Tabs
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-tabs/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,28 @@
---
title: How to Install Node Js and Npm on Windows
---
## How to Install Node Js and Npm on Windows
Installing Node.js and Npm on Windows is very straightforward.
First, download the Windows installer from the <a href='https://nodejs.org/' target='_blank' rel='nofollow'>Node.js website</a>. You will have the choice between the **LTS** (Long Term Support) or **Current** version.
- The **Current** version receives the latest features and updates more rapidly
- The **LTS** version foregos feature changes to improve stability, but receives patches such as bug fixes and security updates
Once you have selected a version meets your needs, run the installer. Follow the prompts to select an install path and ensure the **npm package manager** feature is included along with the **Node.js runtime**. This should be the default configuration.
Restart your computer after the installation is complete.
If you installed under the default configuration, Node.js should now be added to your PATH. Run command prompt or powershell and input the following to test it out:
> node -v
The console should respond with a version string. Repeat the process for Npm:
> npm -v
If both commands work, your installation was a success, and you can start using Node.js!
#### More Information:
For more information and guides, please visit the <a href='https://nodejs.org/en/docs/' target='_blank' rel='nofollow'>Node.js docs page</a>.

View File

@ -0,0 +1,12 @@
---
title: Increment a Number with JavaScript
---
You can easily increment or add `1` to a variable with the `++` operator.
i++;
is the equivalent of
i = i + 1;
**Note** The entire line becomes `i++;`, eliminating the need for the equal sign.

View File

@ -0,0 +1,15 @@
---
title: Tutorials
---
## Tutorials
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,6 @@
---
title: Invert Regular Expression Matches with JavaScript
---
Use`/\S/gi`; to match everything that isn't a space in the string.
You can invert any match by using the uppercase version of the selector `\s` versus `\S` for example.

View File

@ -0,0 +1,23 @@
---
title: Iterate with JavaScript for Loops
---
The most common type of JavaScript loop is called a `for loop` because it runs `for` a specific number of times.
var ourArray = [];
for(var i = 0; i < 5; i++) {
ourArray.push(i);
}
ourArray will now contain [0,1,2,3,4]
## More about for loops
for(var i = 0; i < 5; i++) { // There are 3 parts here
There are three parts to for loop. They are separated by semicolons.
1. The initialization: `var i = 0;` - This code runs only once at the start of the loop. It's usually used to declare the counter variable (with `var`) and initialize the counter (in this case it is set to 0).
2. The condition: `i < 5;` - The loop will run as long as this is `true`. That means that as soon as `i` is equal to 5, the loop will stop looping. Note that the inside of the loop will never see `i` as 5 because it will stop before then. If this condition is initially `false`, the loop will never execute.
3. The increment: `i++` - This code is run at the end of each loop. It's usually a simple increment (`++` operator), but can really be any mathematical transformation. It is used to move the counter (`i`) forward (or backwards, or whatever.

View File

@ -0,0 +1,11 @@
---
title: Iterate with JavaScript While Loops
---
Another type of JavaScript loop is called a `while loop` because it runs `while` something is true, and stops once that something is no longer true.
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}

View File

@ -0,0 +1,40 @@
---
title: JavaScript for Loops Explained
---
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement or a set of statements executed in the loop.
The for loop has the following syntax:
for (<a href='http://forum.freecodecamp.com/t/javascript-while-loop/14668' target='_blank' rel='nofollow'>initialization]; [condition]; [final-expression]) {
code block to be executed
}
[initialization] is executed before the loop (the code block) starts.
[condition] defines the condition for running the loop (the code block).
[final-expression] is executed each time after the loop (the code block) has been executed.
## Example in JavaScript:
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
From the example above, you can read:
[initialization] sets a variable before the loop starts (var i = 0).
[condition] defines the condition for the loop to run (i must be less than 5).
[final-expression] increases a value (i++) each time the code block in the loop has been executed.
## Why we need "for loops"?
For loops are used to loop through a block of code a known number of times. Sometimes it is the computer that knows how many times, not you, but it is still known.
Checkout some of our other articles on loops:
* [While Loop</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-in-loop/14665' target='_blank' rel='nofollow'>For In Loop</a>

View File

@ -0,0 +1,59 @@
---
title: Page Redirects Using JavaScript
---
## Page Redirects Using JavaScript
If you're trying to redirect a user to another page, you can easily use JavaScript to accomplish this task. It is important to note the following:
Even if you have the jQuery library loaded in your scripts, you might wish to use the pure JavaScript solution for page redirects for efficiency purposes.
There are several different ways to go about this, but the simplest way is to use the `window.location` object to send the user to the page you wish them to be redirected to. The `window.location` object can use any valid URL value such as `http://www.yoururl.com`, `somepage.html`, etc.
```javascript
window.location = 'http://www.yoururl.com';
// window.location = 'somepage.html';
// etc.
```
### Special Case Redirect
You can use a special redirect method that is, by default, attached to the `window.location` object in every major browser named `replace()`. This method accepts the same valid URL values as just using `window.location`.
Here is an example of using this method (it will still work the same as just using `window.location` in other browsers):
```javascript
window.location.replace('http://www.yoururl.com');
// window.location.replace('somepage.html');
// etc.
```
### A Simple Timed Redirect Using JS
Here is an example of a simple timed redirect using the `setTimeout()` function. Timed redirects are useful so that you can explain to the user, via the content on the redirect page, the reason why they are being redirected to another page.
```javascript
// the 5000 below is 5000 milliseconds which equals 5 seconds until the redirect happens
// keep in mind that 1 second = 1000 milliseconds
setTimeout(function () {
window.location = 'http://www.yoururl.com';
// window.location = 'somepage.html';
// etc.
}, 5000);
```
### Fallback
Sometimes users browse the internet with JavaScript disabled, and this would obviously present problems with a JS dependant redirect solution. I recommend setting a `<meta>` element that will refresh the browser with the new location. I would set the time for this meta element to be a second after the JS redirect is supposed to take place. So, if you have a redirect that happens in JS after 5 seconds, set the `<meta>` element redirect to take place at 6 seconds.
Place the `<meta>` element within the `<head>` of your document like so:
```html
<head>
<!-- Change the 6 below to however many seconds you wish to wait until redirection to the new page. Change the portion after "URL=" to the URL of your choice. This can be a local page: URL=somepage.html, a web address: URL=http://www.yoururl.com, or any other valid URL. It is important to note the semicolon between the number of seconds to refresh and the URL. -->
<meta http-equiv="refresh" content="6;URL=http://www.yoururl.com">
</head>
```
Keep in mind that not all browsers support the `<meta>` element (I'm looking at you, older versions of IE, and Safari), but most modern browsers do (Microsoft Edge, Google Chrome, Mozilla Firefox, Opera).

View File

@ -0,0 +1,6 @@
---
title: Perform Arithmetic Operations on Decimals with JavaScript
---
In JavaScript, you can perform calculations with decimal numbers, just like whole numbers.
var quotient = 4.4 / 2.0; // equals 2.2

View File

@ -0,0 +1,10 @@
---
title: Store Multiple Values in One Variable Using JavaScript Arrays
---
With JavaScript array variables, we can store several pieces of data in one place.
You start an array declaration with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:
var sandwich = ["peanut butter", "jelly", "bread"]
`myArray = [2,'j'];`

View File

@ -0,0 +1,8 @@
---
title: Subtract One Number from Another with JavaScript
---
We can also subtract one number from another.
JavaScript uses use the - symbol for subtraction.
var difference = 45 - 33;

View File

@ -0,0 +1,65 @@
---
title: JavaScript Version of Jquerygetjson
---
If you want to work with json files with just vanilla JavaScript.
## IE8+
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.responseText);
} else {
// Error :(
}
}
};
request.send();
request = null;
## IE9+
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
## IE10+
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();

View File

@ -0,0 +1,16 @@
---
title: Use the JavaScript Console
---
Both Chrome and Firefox have excellent JavaScript consoles, also known as DevTools, for debugging your JavaScript.
You can find Developer tools in your Chrome's menu or Web Console in FireFox's menu. If you're using a different browser, or a mobile phone, we strongly recommend switching to desktop Firefox or Chrome.
You can also use <a href='https://repl.it/' target='_blank' rel='nofollow'>https://repl.it/</a> to run code online.
This is how you print to the console:
console.log('Hello world!')
Also You can print an error log in the console with this code:
console.error('I am an error!')

View File

@ -0,0 +1,74 @@
---
title: Using Anonymous Functions for Private Namespacing in Your JavaScript Apps
---
Let's take a look at what a namespace is when it comes to building JavaScript applications and some of the benefits from using a private namespace when building your apps.
**Please note that this article references anonymous self-executing functions. If you're unaware of what this is, please read this excellent article by Noah Stokes: <a href='http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write' target='_blank' rel='nofollow'>Self-Executing Anonymous Functions or How to Write Clean Javascript</a>. This article will go into detail about anonymous self-executing functions.**
## What is a Namespace?
To put it simply, a namespace is just a section of code that has its own space. When you first begin writing JS apps, you generally just type the code out and run it. This puts all of the code into what's known as the **global namespace**, which contains all of the code for the window you're working in.
If you keep all of your code in the **global namespace**, though, you can run into problems with collisions, naming conventions, etc. especially in large JS applications/games.
Let's take a look at an example of how using only the **global namespace** to develop a game is a bad idea.
So, let's say we have a game that is keep tracking of the points that the player has:
var points = 0;
A lot of games track points to add a competitive edge to the game. By simply typing that line into a script, we've created a variable named _points_ that can track the points gained by the user.
And that's all fine and well, but let's say that we have a more advanced user playing the game. This user knows how to look at the source of a web page, and so this person takes a peek at the source behind the JS game and realizes that the _points_ variable is just sitting there in the **global namespace**. An evil smirk descends across their face as they contemplate the points they can achieve! They decide that they don't want to wait to beat some baddies up, or smash some mushrooms, or what have you, to rack up a bunch of points. They want their points now! Well, how does _a quadrillion billion million_ points sound?! So, they load up the console on their favorite browser, and simply type into the console:
points = 34750925489459203859095480917458059034;
Once the user hits enter, the _points_ variable is updated in the game. Now, the user has a truly humongous, and likely unrealistic, amount of points in the game, and he can brag to his friends that no one can possibly beat his awesome score.
So, how do we prevent this from occurring? This is where **private namespaces** come into play.
## Private Namespaces
**Private namespaces** allow developers to put their code into sections (or **namespaces**). These sections operate independently of each other but can still read and write from the **global namespace**.
To break this down into simpler terms from a real life scenario, let's say you are working in an office building. You have your own office, and you see others with their own offices. Each office is locked, and only the person who owns the office has a key to this office. Let's also say that you have some type of new super lock that makes your office impenetrable by any other person in the building. Let's consider the office building itself as the **global namespace** and each office as a **private namespace**. You don't have access to anyone else's office nor do they have access to yours. But, each one of you have access to the rest of the office building, whether that's getting coffee, grabbing a snack, etc. Each one of you can grab something from the **global namespace** (or create/modify something there), but you can't create/modify/grab anything from each other's offices; you can only create/modify/grab from your own **private namespace**/office.
## Achieving a Private Namespace
So, how do we achieve this **private namespace** in JavaScript? Use an anonymous self-executing function! If you didn't read the article by Noah Stokes, <a href='http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write' target='_blank' rel='nofollow'>Self-Executing Anonymous Functions or How to Write Clean Javascript</a>, please do so now. This article will go into detail about anonymous self-executing functions.
Let's take a look at using that _points_ variable from earlier, but let's separate it into a **private namespace**:
//The most common way you'll see an anonymous self-executing function
(function () {
var points = 0;
})();
//This is just one of many more alternative ways to use an anonymous self-executing function
/*
!function () {
var points = 0;
}();
*/
Now, when the user gets to the page, they will be unable to open up the console in their browser and change the value of the points variable as they wish! Awesome!
## Namespace and Document Interaction
The above code was but one use for using an anonymous self-executing function to give code its own **private namespace**. Keep in mind that namespaces only affect JS code (variables/arrays/objects/etc.), not code that pertains to the document itself.
Any code within a namespace still has the same access to the HTML document, and CSS, as you would normally in the **global namespace**. Take a look at the next two code samples. They both perform the same functionality, and neither is more beneficial, or more efficient, than the other.
<script type="text/javascript">
(function () {
document.querySelector('body').style.background = 'blue';
})();
</script>
is the same as:
<script type="text/javascript">
document.querySelector('body').style.background = 'blue';
</script>
Keep in mind that this is just one way to use namespaces in JavaScript applications. Adapt your code to what best fits the situation at hand.

View File

@ -0,0 +1,83 @@
---
title: What Does JavaScript Void 0 Mean
---
## What Does JavaScript Void 0 Mean
**JavaScript's void operator evaluates an expression and returns undefined**.
Using console to verify the same :-
![ConsoleOutput](https://github.com/srawat19/-Guide_Images/blob/master/VoidConsole.PNG?raw=true)
***Note*** :- **void** irrespective of any value passed along , *always returns **undefined** as shown above*.
But, **void with operand 0 is preferred**.
**Two ways of using operand 0 -> void(0) or void 0.** Either of them is fine.
#### When to use Javascript void (0) ?
When on link click, you don't want the browser to load a new page or refresh the same page( depending on the URL specified ).
Instead,perform the JavaScript attached to that link.
#### Sample Example 1 with Javascript void (0) :
```html
<html>
<body>
<a href="javascript:void(0);alert('Hello ! I am here')">Click Me</a>
</body>
</html>
```
#### Output :
When clicked on ClickMe link,an alert pops up as below :
![Output1](https://github.com/srawat19/-Guide_Images/blob/master/voidOutput1.PNG?raw=true)
#### Sample Example 2 with Javascript void (0) :
```html
<html>
<body>
<a href="javascript:void(0)" ondblclick="alert('Hi,i didnt refresh the page')" )>Click Me</a>
</body>
</html>
```
#### Output :
When you double click the link,an alert will popup without any page refresh.
#### Sample Example 3 with Javascript void (0) :
```html
<html>
<body>
<a href="javascript:void(0);https://www.google.co.in/"
ondblclick="alert('Hello !! You will see me and not get redirected to google.com ')">Click Me</a>
</body>
</html>
```
#### Output :
When you double click the link,an alert will popup,closing it will also not redirect to google.com.
#### Sample Example without Javascript void (0) :
```html
<html>
<body>
<a href="https://www.google.co.in/" ondblclick="alert('Hello !! You will see me and then get redirected to google.com even if not needed')">Click Me</a>
</body>
</html>
```
#### Output :
When you double click the link,an alert will popup, closing it will redirect to google.com.
#### Conclusion :
**void** operator is useful when you need to prevent any unwanted page refresh or redirection.
Rather,perform some javascript operation.
#### More Information:
1) <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void' target='_blank' rel='nofollow'>Mozilla Docs</a>
2) <a href='https://www.quackit.com/javascript/tutorial/javascript_void_0.cfm' target='_blank' rel='nofollow'>Understanding void 0</a>

View File

@ -0,0 +1,28 @@
---
title: Write Reusable JavaScript with Functions
---
In JavaScript, we can divide up our code into reusable parts called functions.
Here's an example of a function:
function functionName() {
console.log("Hello World");
}
You can `call` or `invoke` this function by using its name followed by parentheses, like this:
functionName();
Each time the function is called it will print out the message "Hello World" on the dev console. All of the code between the curly braces will be executed every time the function is called.
Here is another example:
function otherFunctionName (a, b) {
return(a + b);
}
We can `call` or `invoke` our function like this:
otherFunctionName(1,2);
and it will run and return its return value to us.