window.addEventListener ?
window.addEventListener("load", loaded, false) :
window.attachEvent && window.attachEvent("onload", loaded);
function loaded() {
  gsap.registerPlugin(ScrollTrigger);
  gsap.registerPlugin(DrawSVGPlugin);
  gsap.registerPlugin(MotionPathPlugin);

  ScrollTrigger.defaults({
    toggleActions: "restart pause reverse pause",
    markers: false,
    scrub: 1
  });
  // Scrolled
  const tlScrolled = gsap.timeline({
    scrollTrigger: {
      trigger: "body",
      start: "50px top",
      endTrigger: "footer",
      end: "bottom top",
      toggleClass: "scrolled"
    }
  });
  // On page load
  document.querySelectorAll(".anim").forEach(e => e.style.visibility = "visible");
  document.querySelectorAll(".anim2").forEach(e => e.style.visibility = "visible");
  const tlHeaderLoad = gsap.timeline();
  tlHeaderLoad
    .from(".anim", {y: -200, opacity: 0, duration: 0.8, delay: 0.5, stagger: 0.3});
  if (document.querySelector("#intro")) {
    tlHeaderLoad.from("#intro .cta a", {y: 300, opacity: 0, duration: 0.8}, 0);
  }
  // On page load: trip
  if (document.querySelector("#trip-header .trip-map")) {
    if (document.querySelector("#trip-header .map-outline")) {
      tlHeaderLoad.from("#trip-header .map-outline", {opacity: 0, drawSVG: 0, duration: 2}, 0);
    }
    tlHeaderLoad
    .addLabel("drawTrail", 1.2)
    .from("#trip-header text", {opacity: 0, stagger: 0.2}, "drawTrail")
    .from("#trip-header .trail", {drawSVG: 0, duration: 2.5}, "drawTrail");
    gsap.to("#trip-header .trip-map", {y: 200, opacity: 0, transformOrigin: "left bottom", scale: 1.5, scrollTrigger: {trigger: "#trip-header .trip-map", start: "top top", end: "bottom top"}});
  }
  document.querySelector("#nav-toggle").addEventListener("click", () => {
    document.querySelector("nav").scrollTo(0,0);
  });
  // Home page
  if (document.querySelectorAll("#intro li").length > 0) {
    const panels = gsap.utils.toArray("#intro li");
    const createPanel = (panel => {
      master.addLabel(`panel${panel}`);
      master.add(panel);
      const tl = gsap.timeline({});
      tl
        .set("#" + panel, {zIndex: 10})
        .to("#" + panel + " .overlay", {opacity: 0.5, duration: 1.4}, 0)
        .fromTo("#" + panel, {opacity: 0}, {opacity: 1, duration: 2}, 0)
        .fromTo("#" + panel + " img", {scale: 1.06}, {scale: 1, duration: 6, ease: "none"}, 0)
        .to("#" + panel + " .overlay", {opacity: 1, duration: 1}, "-=1")
        .set("#" + panel, {zIndex: 9});
      return tl;
    });
    const panelsAfterFirst = panels.slice(1);
    const master = gsap.timeline({repeat: -1});
    panelsAfterFirst.forEach(panel => master.add(createPanel(panel.getAttribute("id"))));
    const panelFirst = panels[0].getAttribute("id");
    master.add(createPanel(panelFirst));
    master.set("#" + panelFirst, {opacity: 1}, 0);
    master.set("#" + panelFirst + " img", {scale: 1}, 0);
    gsap.to("#intro .content", {transformOrigin: "0 100%", scale: 2, opacity: 0, scrollTrigger: {trigger: "#intro", start: "top top", end: "bottom top"}});
    // Categories
    gsap.fromTo("#categories", {x: 500}, {x: -200, duration: 1, scrollTrigger: {trigger: "#categories", start: "top bottom", end: "bottom top"}});
  }
  // Tour days path
  if(document.querySelector("#path-days") != null){
    const pathContainer = document.querySelector(".path");
    const pathTop = document.querySelector("#path-top");
    const pathBase = document.querySelector("#path-base");
    const pathLength = pathBase.getTotalLength();
    const pathPos = document.querySelector("#path-position");
    //gsap.set(pathTop, { strokeDasharray: pathLength + ' ' + pathLength });
    let h, p;
    function followPath() {
      h = (0.5 * window.innerHeight - pathContainer.getBoundingClientRect().top) / pathContainer.getBoundingClientRect().height;
      p = pathLength - pathLength * h;
      //gsap.set(pathTop, {strokeDashoffset: p });
      gsap.set(pathPos, { motionPath: { path: pathBase, end: h, align: pathBase, offsetX: -25, offsetY: -25, rotate: 0.1 } });
    }
    followPath();
    window.onscroll = function() {followPath()};
  }
  // Gallery
  if (document.querySelector(".gallery") != null) {
    gsap.from(".gallery", {x: "30%", scrollTrigger: {trigger: ".gallery", start: "top bottom", end: "top 30%"}});
    if (document.querySelector(".gallery ul li") != null) {
      gsap.from(".gallery .controls", {opacity: 0, y: 400, scrollTrigger: {trigger: ".gallery", start: "top bottom", end: "bottom bottom"}});
      const panels = document.querySelectorAll(".gallery ul li");
      const container = document.querySelector(".gallery ul");
      const btnPrev = document.querySelector(".gallery #prevButton");
      const btnNext = document.querySelector(".gallery #nextButton");
      const len = panels.length;
      const counter = document.querySelector(".gallery .counter span");
      const progress = document.querySelector(".gallery .progress span");
      const dur = 0.7;
      let curr = 0;
      gsap.set(panels[0], {y: 0});
      gsap.to(progress, {width: ((100 / len) * (curr + 1)) + "%"});
      function switchPanel(loc, dir) {
        console.log(loc);
        if (gsap.isTweening(".tween") || loc < 0 || loc > len || curr === loc) {
          return;
        }
        let tl = gsap.timeline();
        tl.set(panels[curr], {zIndex: 100});
        if (dir === 1) {
          tl.fromTo(panels[loc], {zIndex: 101, y: "100%"}, {y: "0", duration: dur, ease: "power1"});
        }
        if (dir === -1) {
          tl.fromTo(panels[loc], {zIndex: 101, y: "-100%"}, {y: "0", duration: dur, ease: "power1"});
        }
        tl.to(panels[curr], {zIndex: 100, y: "85vh", duration: 0.1});
        counter.textContent = ("0" + (loc + 1)).slice(-2);
        gsap.to(progress, {width: ((100 / len) * (loc + 1)) + "%"});
        curr = loc;
      }
      btnPrev.addEventListener("click", () => {
        if (curr === 0) {
          switchPanel(len - 1, -1);
        } else if (curr > 0) {
          switchPanel(curr - 1, -1);
        }
      });
      btnNext.addEventListener("click", () => {
        if (curr === len - 1) {
          switchPanel(0, 1);
        } else if (curr < len - 1) {
          switchPanel(curr + 1, 1);
        }
      });
      let ts = 0;
      container.addEventListener("touchstart", e => {
        pos = container.getBoundingClientRect();
        if (curr < len - 1) {
          e.preventDefault();
        }
        ts = e.touches[0].clientX;
      });
      container.addEventListener("touchend", e => {
        let te = e.changedTouches[0].clientX;
        if (ts < te - 2 && curr === 0) {
          e.preventDefault();
          switchPanel(len - 1, -1);
        } else if (ts < te - 2 && curr > 0) {
          e.preventDefault();
          switchPanel(curr - 1, -1);
        } else if (ts > te + 2 && curr === len - 1) {
          e.preventDefault();
          switchPanel(0, 1);
        } else if (ts > te + 2 && curr < len - 1) {
          e.preventDefault();
          switchPanel(curr + 1, 1);
        } else {
          return;
        }
      });    
    }
  }
}
 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");