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.


Flexbox - Weird parts

This is a summary of all the instructional videos on the site Flexbox.io by Wes Bos.

Github Link of my mini-projects on Flexbox.


Flexbox

There are 2 components of flexbox: flex container and flex item
The element with display:flex; is the container, and all the elements that are direct children to it are flex items.
A display:inline-flex also exists, if you want a flexbox to take just the amount of space it requires to bear all its children. 

flex-direction
There are 2 axes in Flexbox
main axis: by default from left to right and
cross axis: by default from top to bottom

If you set flex-direction:column; the main axis becomes top to bottom and cross axis from left to right
If you use flex-direction: row-reverse - The axis goes from right to left
Similarly for column-reverse - bottom to top

flex-wrap
This causes the elements to shift along the cross axis if the space in the main axis becomes full.
nowrap is default
wrap is one option.
wrap-reverse is also an option, but it causes the cross axis to go from bottom to top, keeping the main axis the same.

*Without wrap and each item set to 33.33% width and with 10 items, again, without wrap, all 10 elements will appear in one row.
But if we need actual 33.33% width for each item, we set it to wrap. So element 1,2,3 appear on one line, the next ones 3,4,5 appear on the next and so on.

Calc is a new feature in CSS that lets us perform arithmetic on an assortment of units.
calc(33.33% -20px) in CSS

Margin kind of breaks flexbox because margin lies outside the box in a CSS box model


Order
The default order for everything is 0
Anything greater than 0 goes at the end
Negative order comes first, i.e before the default items with no order set.
Order is useful in responsive design

*When you select elements they get selected in original order in HTML document. So it should be carefully used especially where text has to be copied.


Aligning and centering
justify-content: How the items are aligned on the main-axis. Possible values:
flex-start
flex-end
center
space-between
space-around
mistyrose is a nice color.

align-items: How the items are aligned in the cross-axis
Needs to have some height for it to work.
Default is set to stretch
flex-start: top
flex-end: bottom
*baseline: The bottom of the text in all items is aligned at the same level, irrespective of the size of each item.
If you flip axes, i.e use flex-direction:column; the baseline aligns on left side instead of the bottom.

align-content:  Works on cross axis. Works only if we have multiple lines of content. Needs wrap. Deals with the extra space in cross axis.
Default is stretch.
With align-content set to center, to bring item#10 to the center, use justify-content:center.


justify-content:center.




align-self applies an exception to a flex-item attribute. So if all items are aligned at flex-start, we can apply flex-end to just one item.
align-self: flex-end;


flex-grow is how much of the extra space available should that element take. If element a has flex-grow:1; and no other element has flex-grow, all of the extra space will be given to element a.

flex-shrink is how should the element behave when there is no extra space, and lesser space than enough to hold the natural size of the elements. So if flex-shrink is 1 for all elements, all the elements will shrink equally.
if flex-shrink:10; on element a, a shrinks 10 times as much as the other elements do.

*if you set min-height:100vh; to a flex-direction:column, it flows from top to bottom. But if you assign height:100vh, it causes the elements that can’t fit in 100vh due to their flex-basis to move into another column, from top to bottom.

*If you want to use wrap, the parent needs to have some width

default align-items is set to stretch. If you set align-items to center, the sizes of elements may not be stretched to equal others but may vary from element to element.


flex:0 1; means do nothing on extra space

And that pretty much sums it up!

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

Friday, January 6, 2017

JS30 Challenge Day6 - Type ahead (Difficult)


Disclaimer: For this project, I did a ton of copy-paste. Maybe I should revisit this project later for study.

transform: perspective(100px);
Sets the z=0 plane further behind, by the given value

background: linear-gradient(to bottom, white 0%, black 100%);
The % in linear gradient means that that color should reach its full hue by that location in the gradient.

fetch(url);
We used this command in combination with the 'then' property to retrieve the json data from the given city-state website.

'…' is spread. It is used to spread all arguments passed to the array as their own elements

How to put a variable into regular expression
const regex = new RegExp(wordToMatch, ‘gi’);
where g is for global
and i is for case insensitive
wordToMatch is our variable
Then do element.match(regex) or element.replace(regex)

We use filter because we want to apply a function to every single element in the array

'change' can also be an event in addEventListener
Especially handy for inputs
The change event only fires when you step outside that input
So it's a good idea to tie the element up with the 'keyup' event as well

Don't make me think - highlights - Ch.6

Ch. 6. Street signs and bread-crumbs
Designing navigation.


Like a store, there is no clerk to explain the map of the website to you. The “search” functionality fulfills this purpose.

Difference between real world and web world:
No sense of scale: In real life, we can have a rough estimate of how large a store is. But a website could have huge corners we have no idea about seeing the home-page. We can’t tell how large a website is, usually.

No sense of direction or location in websites as opposed to the real world.

Don’t use breadcrumbs instead of page name!

Tabs are a great way to show a user where he/she is. The chapter talks about some reasons why tabs are great. Also, tabs were probably invented by Leonardo Da Vinci.

Thursday, January 5, 2017

JS30 Challenge Day 5 - Flexbox Gallery

Day 5


This was more of a CSS heavy project

It reminded me that we can use cubic-bezier in transition
transition:
    font-size 0.7s cubic-bezier(0.61,-0.19, 0.7,-0.11),
    flex 0.7s cubic-bezier(0.61,-0.19, 0.7,-0.11),

It reminded me that we can set flex-direction to column
flex-direction:column;

And finally, I learned the includes function:

e.propertyName.includes('flex')

JS30 Challenge Day4 - Array functions

Day 4


Some basic concepts revisited:

Filter:
You pass a function to a filter which will loop over every item in the array

We can use console.table instead of console.log to display it pretty 

I learned a fancy and compact way to return a value instead of an if-statement returning ‘true’.

const fifteen=inventors.filter(inventor => inventor.year <1600 && inventor.year>= 1500);

Map:
Takes in an array, modifies it and returns a new array

We use + for concatenation in JS and . in PHP

Reduce:
Builds something on each entry

const tot = inventors.reduce((total,inventor) => {return total+ inventor.passed-inventor.year},0);

The 0 at the end is to set the total to an initial value of 0
So following this idea, you could as well initialize it to a 5, for example, for some different kind of functionality.

Reminder: querySelectorAll does not return an Array but returns a NodeList
Array.from(some_nodeList); converts a NodeList into Array

textContent:
const de= links.map(link=> link.textContent);
link.textContent returns the names enclosed within ‘a’ tags where links is a list of ‘a’ tags on the page

Reduce explained:

const transport = data.reduce(function(obj,item){

      if(!obj[item]) obj[item]=0;
      obj[item]++;
      return obj;

    },{});

In the code above, obj is an element passed to the reduce function which will gather data over each iteration. For each unique element in an array, an obj will be created. The name of the element goes into the index of the obj. So every time an element is found, the value of that item ( the element from the data array) will increase by 1 in the obj object. To initialize the object as a blank object, we have added {} at the end.

In short, the parameters of a reduce function should match the structure of an element in the calling array. This could be a name value pair or simply a variable like total which accrues count over time and is not part of the array element originally. It may act as just another variable as we saw in the first usage of reduce function or it may act as an object containing its own processed values.


Wednesday, January 4, 2017

JS30 Challenge Day 3 - Image Editor (CSS Variables)

Day 3 

Github link

In the previous project, I had created a new branch to make changes to the code.
Today I merged that branch with the master.
To merge a branch, checkout into the main branch you want to keep
and then type
git merge secondary-branch-name
in the terminal

HTML & CSS

The for property of a label binds the label to the element it is meant to address.
<label for=“specifies the element this label is bound to”>

Writing CSS for the page, it reminded me to use
*{
margin:0;
padding:0;
}

If we don’t do this, sometimes we get a scrollbar on the browser window because something somewhere started with a non-zero margin or padding.

It also reminded me to put a ./ at the beginning of every path (as in the 'img src' path in this case).
I have encountered situations where I specified the entire path without the prefix given above and the library or plugin just wouldn’t work.

I learned about a new input type, 'range', which is basically a slider that has a default “value” a min value and max value.
<input type=“range” min="10" max="100" name="blur" value="20">
Notice that the min and max values have to be in quotes

data-sizing is a custom attribute we used in this project.

I learned about another input type, called color.
<input type=“color” value=“ffc600>

Can we change the color of the slider in range?
Probably. The slide itself is called ‘track’ and the bob is called ‘thumb’. These can be controlled only by using browser prefixes.
input[type=range]::-browser-prefix-thumb
{
background: coral;}
I tried doing it without prefixes but it didn’t work, so I left it at that.

To scale the inputs down, I just put a width to 'input' elements
input{ width: 100px; }

JS

CSS variables! Doesn’t that sound great? It’s a new feature.
And though SASS can have variables, they after processing get cast into something fixed and not dynamic. That’s how CSS variables differ from SASS variables.

I learned about :root, the selector for the base element in HTML.
You need to declare the variable on some element. And we will do that on :root

So basically, we declare all the variables in :root
For example,
:root{
—blur: #ffc600;
}
and wherever we want to use the CSS variable, we use
var(—variableName)
For example, for blur, we could use
filter:blur(var(—blur));

querySelectorAll(); does not return an array. It returns a NodeList which is like an array but without most of the functions in the prototype.

Once again, it reminded me that you can’t use forEach on its own. It has to be with some element. Like input.forEach();

I learned about mousemove event. The second M is not capital
Just like we learned about transitionend event in the previous project.

this.dataset returns all the “data” prefixed properties and their values

And finally, a bunch of new terms in
document.documentElement.style.setProperty();
What is documentElement?
From MDN, we find out:
document.documentElement returns the root element of the document for example, the HTML element for HTMLdocuments.

style.setProperty() takes in the name of the property, for example, the “name” attribute assigned to an input, in our case spacing|blur|base, and takes in the value for that element, as in, the value assigned to the “value” attribute in that element. The value also must have a unit-suffix if it applies (like px, s, pt, etc.).

And that's a wrap up :)

Monday, January 2, 2017

JS30 Challenge Day2 - Clock

Day 2


This exercise refreshed my memory about the cover parameter for background-size.
background-size: cover;
This fits the image in a way that covers the entire window with that image, while some parts of the image might go out of the window.

rem unit
This is a relative unit which multiplies the font-size of body element with the value specified.
So if the body font size is 10px, 2rem would equal 20px.

transform-origin:100%; //moves the origin of rotation along x-axis
So a 100% transform-origin would shift the origin to the rightmost end of the element (in our case, hand).

In the original exercise, all the hands are the same length and color
I decided to make the hands different colors and lengths
From longest to shortest, I have placed the hands on top of one another in respective order.

Because the dimensions of the hands had to be different, and given that the initial hand we draw is in horizontal position,
I gave 50% width to the second hand which makes the hand touch the center of the dial.
In minute hand however, I made the width 40% and what we get is a hand that does not touch the center of the dial. Hence we need to give it a 10% margin.
Similarly for hour hand, 30% width requires 20% margin.
The logic is that the addition of width of the hand and its left margin should be 50%.

Then, I learned about transition-timing-function
The normal values are ease-in, ease-out, ease-in-out
But we can customize the transition using a cubic bezier curve, like so:
transition-timing-function: cubic-bezier(0.1,2,7,0.58,1);

JS

The setInterval function runs a function passed to it on every interval specified
setInterval(functionName, milliseconds)
We have used it to call setDate function after every second. 
setDate is the function in which all the hours, minutes and seconds are retrieved and degrees for the hands are calculated and applied

For the final extra bit, I was able to remove the glitch that occurs at every 0th second.
When any hand transitions from final state to initial state, because the number of degrees reduce, the hand makes a (reverse) anti-clockwise motion to reach the 0 degree mark.
Because the transition is set at 0.05s, a slight hint of this animation is visible.

To bypass this, just change the transition to ‘all 0s’ using javascript.
I created a class called .fast
It contains the following line of code
transition: all 0s;

At every 0, I add the class and at every 1, I remove the class thus returning the hand to the cubic bezier curve at 0.05s

if(seconds===0)
secondHand.classList.add(‘fast’);
if(seconds===1)
secondHand.classList.remove(‘fast’);

And voila! All done.

Sunday, January 1, 2017

Don't make me think summary - Ch.3, 4 & 5

Ch. 3.Billboard design 101
Design pages for scanning not reading

1.Create a visual hierarchy
Relationships, especially hierarchical ones, should be clearly shown on the page. This includes element-size, grouping and nesting. Newspapers are good examples of this.

2.Take advantage of conventions
Designers are often afraid to follow conventions because they think re-inventing the wheel is often the ways to go. But conventions bolster the usability and make scanning easy and fast.

3.Break pages into clearly defined areas

4.Make it obvious what's clickable
Users are often looking for the next thing to click.

5.Minimize noise

Ch. 4.Animal, vegetable or mineral?
Why users like mindless choices

*Krug's second law of usability:
It doesn't matter how many times I have to click as long as each click is mindless and unambiguous.

"Three mindless, unambiguous clicks is equal to one that requires thought"

Ch. 5.Omit words

*Krug's third law of usability
Get rid of half the words on the page. Then get rid of half of what's left.

A sentence should contain no unnecessary words, a paragraph, no unnecessary sentences.
Happy talk or small talk must be eliminated.
Instructions must die.