Showing posts with label JS30. Show all posts
Showing posts with label JS30. Show all posts

Saturday, February 4, 2017

JS30 Challenge Day 15 - localStorage



Last but not the least, and the longest one of them all!
I have added some extra functionality to my solution in this one.

form elements have a reset method in them
this.reset();

JSON.stringify();
JSON.parse();

    localStorage.setItem('items',JSON.stringify(items));

For the clearAll function, 
I had to define items as let instead of const because I need to reset it to [] an empty array in the clearAll function.

UncheckAll was pretty straightforward.
Just remember to define the new buttons outside the form, because we have already used event delegation on the form.

An event delegation is like giving a task to a responsible parent.

If you give the task to its kids, they may not behave, so you delegate it.

JS30 Challenge Day 30 - Whack a mole


'click' event has a .isTrusted property which can check for fake clicks generated by javaScript.

random*(max-min)+min; //explained:
random always assumes a value between 0 and 1
max-min gives us the difference between the two edge values
so a decimal between 0 and 1 is multiplied times the difference, which can possibly give us a max of the difference times 1, the max possible value, or it could give us a zero.
The final + min ensures that the minimum possible value if the difference between max and min is 0, will be the min value itself. So it basically offsets the value of max-min by the value of min itself, so we get a valid number!

Friday, February 3, 2017

JS30 Challenge Day 29 - Timers


We can't use:

setInterval(seconds,{
seconds—;
});

Sometimes when the browser is not active, it might pause the setInterval function. Pauses while scrolling in IOS.

*clearInterval alwaysneeds a variable name of a setInterval to stop it.

setInterval does not run immediately.
It needs 1 sec to start.

element.textContent = display;
Note: Use textContent over innerText.
innerText is IE specific and does not cover all elements

document.title can be dynamically set in JS. This updates the title of the webpage.

Remember to clearInterval the timer at the beginning of the timer function.

If an element has a name attribute in html, it can be directly selected as document.elementName in the DOM.

EventListener’s name of the event should always be enclosed in single quotes.

Access the value of an element by element.value;

this.reset();

is used to reset a DOM element like a textbox.

JS30 Challenge Day 28 - Video Speed Controller

Here we want to calculate the height of the filled bar.

So we take a Y co-ordinate from the event.
We take the offset at which the top of the parent is.
We subtract the offset from the Y co-ordinate, which gives us just how much of the bar is to be filled, call it Y.

Next we want to calculate the height %
So we divide Y by the total height of the parent.
Y/offsetHeight gives us the decimal %

Multiply that by 100 and we get just how much % of space is to be filled by speed-bar.

After that, we need to find the number associated with that much height and use it as playback rate.
At 0 height it should be 0.4
At 100 height it should be 2.5
so we do percent*(max-min)+min

element.textContent
sets the text value of our bar.

number.toFixed(x);
displays the number with x decimal places


Thursday, January 26, 2017

Javascript 30 Challenge Day 27- Drag and Scroll

Some cursors require a vendor prefix

pageX
The MouseEvent.pageX read-only property returns the horizontal coordinate of the event relative to the whole document.

offsetLeft
The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node.

scrollLeft
The Element.scrollLeft property gets or sets the number of pixels that an element's content is scrolled to the left.

e.preventDefault();
Cancels the event if it is cancelable, without stopping further propagation of the event.


Sunday, January 22, 2017

JS30 Challenge Day 25 - Event capturing and bubbling

When you click on the innermost div, we are also clicking on its parents. So the event bubbles and calls out class ‘three’ then ‘two’ then ‘one’, moving from the innermost div to the outermost.

First, the capture happens in which the browser ripples down from the html to the body to the parents to our coral div. It starts at the coral and it bubbles up, goes on triggering events the way up.

capture:true|false is passed as an object in the third parameter of addEventListener

once: true|false is passed as the fourth parameter to addEventListener and this runs the bubbling or capturing exactly once and then unbinds itself which is similar to a removeEventListener();

e.stopPropagation(); stops the bubbling at the current step.


Saturday, January 21, 2017

JS30 Challenge Day 24 - Sticky Nav

Github Link

I had implemented a scroll to fix nav for fun already before this lesson. But this lesson surely refined it by using window.scrollY, offsetTop, offsetHeight instead of just scrollTop.

scrollY is an integer value of how much from the top the window has been scrolled

offsetTop gives the distance of the top of the element from the top of the webpage.

The HTMLElement.offsetHeight read-only property is the height of the element including vertical padding and borders, as an integer.

position:fixed does not take up space like normal.
so when you scroll towards top, the nav jerks out, and jumps exposing some blank space at the top.

We can fix this by giving padding-top to body.
The amount of padding should be nav.offsetHeight

We need to add + ‘px’ to the variable to make it work.

JS30 Challenge Day 22 - Highlight that Follows Mouse Pointer


Run a function on mouseenter event on any ‘a’ element

element.getBoundingClientRect();
gives us the co-ordinates, width and height of the current element

Added the following code extra:

initialNav=document.querySelector('li').firstChild;
    initialcoords=initialNav.getBoundingClientRect();
    console.log("initial nav", initialNav);

    start={
      left:initialcoords.left+window.scrollX,
      top:initialcoords.top+window.scrollY
    };

    hilite.style.transform=`translate(${start.left}px,${start.top}px)`;
    triggers.forEach(thing=>thing.addEventListener('mouseenter',lightitup));

The above code deals with the position of the highlight first, before it acquires any height, width or offset., 
I have set the initial position to the first Nav element.
By default the initial position is at the top left corner on the screen.

It doesn’t look nice that way because when you select the first highlight, it drags the highlight from the corner.

JS30 Challenge Day 20 - Speech Recognition


SpeechRecognition.interimResults=true;
This makes sure that results are available while we are speaking and not after we are done speaking.

we use document.createElement to create a paragraph and append it to the ‘words’ div which is a contenteditable.

We add an eventListener on ‘result’ event of SpeechRecognition
In the event e, we get e.results which we assign to transcript variable.

e.results is a list, not an array and each 0th element of the list is the text data we need. So we map transcript on result[0]
Then we return transcript and join everything so that it forms a single string.

This works only for one paragraph so we need to set ‘end’ event to run SpeechRecognition.start() again.

p.textContent=transcript;
We finally put transcript into DOM.


We need to run createElement and appendChild inside the result event again so that p does not get replaced in the DOM but creates a new paragraph instead.

JS30 Challenge Day 18 - Reduce


querySelectorAll(‘[data-time]’)
you can have just [expression] to select elements

querySelectorAll gives a nodelist not array

So spread the nodelist into an array

or use Array.from()

Friday, January 20, 2017

JS30 Challenge Day 17 - Sorting Without Articles


thing.innerHTML = Array.map(band=>`<li>${band}</li>`).join(‘’);

If we dont use join while outputting each array item, it gives us commas before each entry, because it toString ’s the array.

Array.sort((a,b) => a>b?1:-1);

Regex:
/^(a |an |the)/i

There has to be a space after each article otherwise it will start picking up words beginning with articles

S30 Challenge Day 16 - Moving Shadow

Github Link

This one was quite mathematical.

I learned this new way of assigning values to variables
const {offsetWidth:width,offsetHeight:height} = hero;
where width and height are variables values are put into.

The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node.

JS30 Challenge Day 14 - Copy and Reference

Github Link

1.Copy
let age=100;
let age2=age;
age2=200;
age will not change to 200

If age is changed, age2 will not change

2.Reference
players and teams are arrays
const team = players;
team[3]="AK";
Here, players[3] also changes to AK

If players is changed, team also changes. So this changes the values both ways.

3.Copy
const team2=players.slice();
changing team2 will not affect players

Changing either one won't change the other
Works for [...players] and Array.from() the same

4.Reference
Just like arrays, objects also pass by reference
To avoid that, we use Object.assign();

const age3=Object.assign({},person,{number:99});
first arg is an empty object, second is the object to fold in, third is the values we want to additionally fold in.
Difference between slice and splice in Arrays

Monday, January 16, 2017

JS30 Challenge Day 13 - Images that slide in


Almost always debounce scroll events to improve performance.
Debouncing means lessening the frequency of detection of that event

window properties:
scrollY
innerHeight

image properties:
offsetTop
height


In the code, the key concept is that the “middle” variable is stuck to the offset of the window as a whole and the “offsetTop” property is stuck to the image. The middle has been adjusted in a way i.e by subtracting image.height/2 from the total value in such a way that when the middle is greater than offsetTop of the image, the center of the image is below halfway off the screen.

Sunday, January 15, 2017

JS30 Challenge Day 12 - KONAMI Code

For a keyup event in JS
the property e.key, as in type of key pressed does not work in Safari

We used join in this program
array.join('');

Reminded me that there is such a property as 'includes'.
It checks if the passed string is contained in the calling object.

Saturday, January 14, 2017

JS30 Challenge Day11 - Custom Video Player

Github Link

Few things I learned in making this video player:

To access the 'data' variables, we use the dataset keyword in JS,
In this case, we used dataset.skip;

We can use textContent property to change what the button reads.

'change' is also an event.

I had to convert the time of the video into a float using parseFloat();

'timeupdate' is an event for video in HTML.

The following events are all small, no caps.
mousedown
mouseup
mousemove

Sunday, January 8, 2017

JS30 Challenge Day10 - Hold shift to select checkboxes (buggy code)


text-decoration:line-through;

const checkboxes=document.querySelectorAll(‘input [type=checkbox]’);
let lastChecked;
function checkIt(e){
let flag=false;
if(e.shiftKey && this.checked){
checkboxes.forEach(checkbox=>{
if(this===checkbox || checkbox===lastChecked){
flag=!flag;
}
if(flag)
checkbox.checked=true;
});
}
lastChecked=this;
}

checkboxes.forEach(checkbox=>checkbox.addEventListener(‘click’,checkIt));

BUG:
The logic in this code is not complete though.
For example:

-a
-b
-c
-d
-e

If you check a to c.
then you uncheck b.
Then you press shift and check b, 

all the checkboxes below c get checked.

JS30 Challenge Day 9 - Dev Tools


    // Regular
    console.log("hi");
    // Interpolated

    console.log("hi %s",'guys');

    // Styled
    console.log("%c superman",'background:blue; color:white;')

    // warning!
    console.warn("oh no");

    // Error :|
    console.error("It's an error");

    // Info
    console.info("info");

    // Testing
    //console.assert(some statement, "what you wanna throw when it is wrong");
    
    // clearing
    //console.clear();

    // Viewing DOM Elements
    console.dir('p');

    // Grouping together
    dogs.forEach(dog=>{
      console.groupCollapsed(`${dog.name}`);
      console.log("hi doggie");
      console.groupEnd(`${dog.name}`);
    });

JS30 Challenge Day 8 - Fun with Canvas


Most of the terms used in this program are canvas specific. I am leaving those terms to the video itself. 

A nice way to set an implicit function
()=>{}
Example:
canvas.addEventListener('mousedown', ()=>isDrawing=true);

An ES6 way to define multiple variables in one statement
 [lastX, lastY] = [e.offsetX, e.offsetY];


Saturday, January 7, 2017

JS30 Challenge Day 7 - Array workout #2


.some
checks at least one thing in the array matches something

getFullYear() is a function, not a property, of Date

find is like filter but instead of returning a subset of the array it returns the first item it finds

A handy way to use {}
console.log(allAdult) gives us the value of allAdult variable
console.log({allAdult}) gives us the allAdult object itself

A great way to use =>

 const isAdult=people.some(person=>{
      const currentYear=(new Date()).getFullYear();
      console.log(currentYear-person.year>=19);
    });

const isAdult=people.some(person=> ((new Date).getFullYear()-person.year)>=19);
    console.log({isAdult});

Reminded me of the Array.splice function.
Example of splice:

b=c.splice(3,2); //starting from index 3, remove 2 elements and    //place them in b