Skip to content

Local master #422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions 07-Pig-Game/starter/script.js
Original file line number Diff line number Diff line change
@@ -1 +1,88 @@
'use strict';

// Constant for setup
const btnRoll = document.querySelector('.btn--roll');
const btnHold = document.querySelector('.btn--hold');
const btnNew = document.querySelector('.btn--new');
const player0 = document.querySelector('.player--0');
const player1 = document.querySelector('.player--1');
const diceRoll = () => Math.trunc(Math.random() * 6) + 1;

let totalScore;
let currentScore0El = document.getElementById('current--0');
let currentScore1El = document.getElementById('current--1');
const player0Score = document.getElementById('score--0');
const player1Score = document.getElementById('score--1');

let diceEl = document.querySelector('.dice');
let playersTurn;
let currentScore;
let playing;

// occurs on save/refresh
const init = function () {
currentScore0El.textContent = 0;
currentScore1El.textContent = 0;
player0Score.textContent = 0;
player1Score.textContent = 0;
diceEl.classList.add('hidden');
currentScore = 0;
totalScore = [0, 0];
player0.classList.add('player--active');
player1.classList.remove('player--active');
playersTurn = 0;
playing = 1;
};

init();

// to switch from one player to another
function switchPlayer() {
playersTurn = !playersTurn ? 1 : 0;
currentScore = 0;
document.getElementById(`current--${!playersTurn ? 1 : 0}`).textContent =
currentScore;
player0.classList.toggle('player--active');
player1.classList.toggle('player--active');
}

btnRoll.addEventListener('click', function () {
if (playing) {
diceEl.classList.remove('hidden');
let currentRoll = diceRoll();
diceEl.src = `dice-${currentRoll}.png`;

if (currentRoll !== 1) {
currentScore += currentRoll;
document.getElementById(`current--${playersTurn ? 1 : 0}`).textContent =
currentScore;
} else {
switchPlayer();
}
}
});

btnHold.addEventListener('click', function () {
if (playing) {
totalScore[playersTurn ? 1 : 0] += currentScore;
document.getElementById(`score--${playersTurn ? 1 : 0}`).textContent =
totalScore[playersTurn ? 1 : 0];

if (totalScore[playersTurn ? 1 : 0] >= 100) {
document
.querySelector(`.player--${playersTurn ? 1 : 0}`)
.classList.add('player--winner');
playing = 0;
diceEl.classList.add('hidden');
} else {
switchPlayer();
}
}
});

btnNew.addEventListener('click', function () {
document
.querySelector(`.player--${playersTurn ? 1 : 0}`)
.classList.remove('player--winner');
init();
});
2 changes: 2 additions & 0 deletions 13-Advanced-DOM-Bankist/starter/index.html
Original file line number Diff line number Diff line change
@@ -21,6 +21,8 @@
alt="Bankist logo"
class="nav__logo"
id="logo"

data-version-number = "3.0"
/>
<ul class="nav__links">
<li class="nav__item">
260 changes: 257 additions & 3 deletions 13-Advanced-DOM-Bankist/starter/script.js
Original file line number Diff line number Diff line change
@@ -7,8 +7,13 @@ const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.btn--close-modal');
const btnsOpenModal = document.querySelectorAll('.btn--show-modal');
const btnScrollTo = document.querySelector('.btn--scroll-to');
const section1 = document.querySelector('#section--1');
/////////////////////////////////////////////////////////

const openModal = function () {

const openModal = function (e) {
e.preventDefault();
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
@@ -18,8 +23,8 @@ const closeModal = function () {
overlay.classList.add('hidden');
};

for (let i = 0; i < btnsOpenModal.length; i++)
btnsOpenModal[i].addEventListener('click', openModal);
btnsOpenModal.forEach( (val) => val.addEventListener('click', openModal))


btnCloseModal.addEventListener('click', closeModal);
overlay.addEventListener('click', closeModal);
@@ -29,3 +34,252 @@ document.addEventListener('keydown', function (e) {
closeModal();
}
});
btnScrollTo.addEventListener('click', function(e) {
const s1coords = section1.getBoundingClientRect();
console.log(s1coords);

console.log(e.target.getBoundingClientRect());

console.log('Current Scroll (x/y) ', window.pageXOffset, window.pageYOffset);

console.log('height/width viewport', document.documentElement.clientHeight,
document.documentElement.clientWidth);


// old way
// window.scrollTo({
// left: s1coords.left + window.pageYOffset,
// top: s1coords.top + window.pageYOffset,
// behavior: 'smooth',
// });

// new way for smooth scroll
section1.scrollIntoView({behavior: 'smooth'});
});

/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//page Navigation

// not optimal adding event listener for all elements with .nav__link class
// document.querySelectorAll('.nav__link').forEach( function(el) {
// el.addEventListener('click', function(e) {
// e.preventDefault();

// const id = this.getAttribute('href');
// console.log(id);

// document.querySelector(id).scrollIntoView({behavior: 'smooth'});
// })
// });



/*
1. Add event listner to common parent elemnt
2. Determine wht element originated the event

*/
document.querySelector('.nav__links').addEventListener('click', function(e) {
e.preventDefault();
console.log(e.target);

// matching strategy
if(e.target.classList.contains('nav__link')) {
const id = e.target.getAttribute('href');
console.log(id);

document.querySelector(id).scrollIntoView({behavior: 'smooth'});

}
})
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////





/////////////////////////////////////////////////////////

console.log(document.documentElement);
console.log(document.head);
console.log(document.body);

const header = document.querySelector('.header');

const allSelections = document.querySelectorAll('.section');
console.log(allSelections);

document.getElementById('section--1');

const allButtons = document.getElementsByTagName('button');

console.log(allButtons);


document.getElementsByClassName('btn');

console.log(document.getElementsByClassName('btn'));

//creating and Inserting elements
// insertAdjacentHTML

const message = document.createElement('div');

message.classList.add('cookie-message');
message.textContent = "We use cookied for imporved functionality and analytics.";

message.innerHTML =
'We use cookied for imporved functionality and analytics. <button class = "btn btn--close-cookie">Got it!</button>' ;

// header.prepend(message);
header.append(message);
// header.append(message.cloneNode(true));



// Delete elements
document.querySelector('.btn--close-cookie').addEventListener('click', function() {
// message.remove();
message.parentElement.removeChild(message);
});



// Styles
// message.style.backgroundColor = "#37383d";
message.style.width = "120%";

// how to get styles

console.log(getComputedStyle(message).height);

message.style.height = Number.parseFloat(getComputedStyle(message).height,10) + 30 + 'px';

//working with custom Css variables
// document.documentElement.style.setProperty('--color-primary', 'orangered');

//Atributes

const logo = document.querySelector('.nav__logo');

// only works if attributes are standard, can not be custom
console.log(logo.alt);
console.log(logo.className);



// setting atributies

logo.alt = 'Beautiful Minimalist logo'
console.log(logo.alt);

console.log(logo.src); // prints absolute path
console.log(logo.getAttribute('src')); // gets realtive path

//Data Attributes

console.log(logo.dataset.versionNumber);


//Classes
// logo.classList.add();
// logo.classList.remove();
// logo.classList.toggle();
// logo.classList.contains();


//Implementing Smooth Scroll



console.log(btnScrollTo);
console.log(section1);



// const h1 = document.querySelector('h1');

// const alertH1 = function(e) {
// alert('addEventListener: Great! ');
// // Method 1 of remove event listener
// // h1.removeEventListener('mouseenter',alertH1);
// }
// h1.addEventListener('mouseenter', alertH1);

// setTimeout( () => HTMLQuoteElement.removeEventListener(
// 'mouseenter', alertH1), 3000);

// h1.onmouseenter = function(e) {
// alert('addEventListener: Great! ')
// };

// Event Propagation: Bubbling and Capturing

// Event Progpagation Practice

const randomInt = (min,max) => Math.floor(Math.random() * (max-min+1) + min);

const randomColor = () => `rgb(${randomInt(0,255)}, ${randomInt(0,255)}, ${randomInt(0,255)} )`;


// document.querySelector('.nav__link').addEventListener('click', function(e) {
// this.style.backgroundColor = randomColor();
// console.log('LINK', e.target,e.currentTarget);
// console.log(e.currentTarget === this);

// // stop propagation
// // e.stopPropagation();
// })
// document.querySelector('.nav__links').addEventListener('click', function(e) {
// this.style.backgroundColor = randomColor();
// console.log('Container', e.target,e.currentTarget);

// })
// document.querySelector('.nav').addEventListener('click', function(e) {
// this.style.backgroundColor = randomColor();
// console.log('nav', e.target,e.currentTarget);
// },);


// DOM traversing

const h1 = document.querySelector('h1');

// going downwards: child

console.log(h1.querySelectorAll('.highlight'));

console.log(h1.childNodes);
console.log(h1.children);

h1.firstElementChild.style.color = 'white';
h1.lastElementChild.style.color = 'blue';

//going upwards: parents

console.log(h1.parentNode);
console.log(h1.parentElement);

// selects closes parent based on class name
h1.closest('.header').style.background = 'var(--gradient-secondary)'

// .closest is like the oppoiste of querySelector
h1.closest('h1').style.background = 'var(--gradient-primary)'

// Going sideways: Siblings

console.log(h1.previousElementSibling);
console.log(h1.nextElementSibling);

console.log(h1.previousSibling);
console.log(h1.nextSibling);

//get all siblings
console.log(h1.parentElement.children);
[...h1.parentElement.children].forEach(function(el) {
if(el !== h1) {
el.style.transform = 'scale(0.5)';
}
});
2 changes: 1 addition & 1 deletion 17-Modern-JS-Modules-Tooling/starter/index.html
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script defer src="script.js"></script>
<script type="module" defer src="script.js"></script>
<title>Modern JavaScript Development: Modules and Tooling</title>
<style>
body {
39 changes: 39 additions & 0 deletions 17-Modern-JS-Modules-Tooling/starter/package-lock.json
15 changes: 15 additions & 0 deletions 17-Modern-JS-Modules-Tooling/starter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "starter",
"version": "1.0.0",
"description": "",
"main": "clean.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"leaflet": "^1.9.4",
"lodash-es": "^4.17.21"
}
}
121 changes: 121 additions & 0 deletions 17-Modern-JS-Modules-Tooling/starter/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Importing Module
// import {addToCart,totalPrice as price, qt} from './shoppingCart.js';
// addToCart('bread', 5);

// console.log(price, qt);

// import * as ShoppingCart from './shoppingCart.js'

// console.log("Importing Module");
// console.log(shippingCost);
//

// console.log(ShoppingCart);

// import add, { addToCart, totalPrice as price, qt } from './shoppingCart.js';
// console.log(price);

// import add, {cart} from './shoppingCart.js';
// add('pizza', 2);
// add('bread', 5);
// add('apples', 4);

// console.log(cart);

// top level await
// console.log('start feteching');

// const res = await fetch('https://jsonplaceholder.typicode.com/posts');
// const data = await res.json();
// console.log(data);
// console.log('Something');

// const getLastPost = async function() {
// const res = await fetch('https://jsonplaceholder.typicode.com/posts');
// const data = await res.json();
// console.log(data);
// return {title: data.at(-1).title, text: data.at(-1).body}

// }

// const lastPost = getLastPost();
// console.log(lastPost);

// // Not very clean
// // lastPost.then(last => console.log(last));

// const lastPost2 = await getLastPost();
// console.log(lastPost2);




// const ShoppingCart2 = (function() {
// const cart = [];
// const shippingCost = 10;
// const totalPrice = 237;
// const totalQuantity = 23;
// const addToCart = function(product, quantity){
// cart.push({product, quantity});
// console.log(`${quantity} ${product} added to cart `);
// };

// const orderStock = function(product, quantity){
// cart.push({product, quantity});
// console.log(`${quantity} ${product} ordered from supplier `);
// };

// return {
// addToCart,
// cart,
// totalPrice,
// totalQuantity
// }
// })();

// ShoppingCart2.addToCart('apple', 4);
// ShoppingCart2.addToCart('pizza', 2);
// console.log(ShoppingCart2);
// console.log(ShoppingCart2.shippingCost);


// // Export
// export.addToCart = function(product, quantity){
// cart.push({product, quantity});
// console.log(`${quantity} ${product} ordered from supplier `);
// };


// // Import
// const { addToCart } = require('./shoppingCart.js');

// import add, { addToCart, totalPrice as price, qt } from './shoppingCart.js';
import add, { cart } from './shoppingCart.js';
import cloneDeep from "./node_modules/lodash-es/cloneDeep.js"

const state = {
cart: [
{product: "bread", quantity: 5},
{product: "pizza", quantity: 5},
],
user: {loggedIn: true},
}


const stateClone = Object.assign({}, state);
const stateDeepClone = cloneDeep(state);
console.log(stateClone);

state.user.loggedIn = false;
console.log(stateDeepClone);



// console.log(price);


add('pizza', 2);
add('bread', 5);
add('apples', 4);

console.log(cart);
30 changes: 30 additions & 0 deletions 17-Modern-JS-Modules-Tooling/starter/shoppingCart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Exporting Module

console.log('Exporting Module ');

//blocking code
// console.log('start fetching users');
// await fetch('https://jsonplaceholder.typicode.com/posts');
// console.log('finish fetching users');


const shippingCost = 10;
export const cart = [];


export const addToCart = function(product, quantity){
cart.push({product, quantity});
console.log(`${quantity} ${product} added to cart `);

}

const totalPrice = 237;
const totalQuantity = 23;

export {totalPrice, totalQuantity as qt}


export default function (product, quantity) {
cart.push({ product, quantity });
console.log(`${quantity} ${product} added to cart `);
}