Tag Archives: javascript30

JavaScript30—Day 3

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 3 — CSS Variables + JS: Demo - Day 3
  1. - - declares variables in CSS as $ in php or var in javaScript. You declare:
    :root{
    --basecolor:#ffc600;
    }
    
    
    and call it out like this:
    p {
     backround-color: var(--basecolor);
    }
    
  2. :root is the deepest level you can go.
  3. If you want update your e.g. style attribute according to input via javaScript variable and name should have the same name, otherwise it wont work:
    
    
    - -basecolor:#ffc600;
  4. NodeList vs array document.querySelectorAll gives NodeList. The difference between NodeList and array is that array gives you all kinds and longer list of methods like map,reduce. List of methods for array:methods list for array List of methods for NodeList: methods for NodeList
Day 3 code on github.

JavaScript30—Day 2

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 2 — CSS-JS clock: Demo - Day 2
  1. Date() gives a chance to get hours, minutes, seconds etc.
    const now = new Date();
    seconds = now.getSeconds();
    minutes = now.getMinutes();
    hours = now.getHours()
    
    
    
  2. transform-origin vs transform:rotate() The first one sets the point around which the transformation takes place. Rotate() is driven by center of the element. More about MDN transform-origin.
Day 2 code on github.

JavaScript30—Day 7

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 7 — Array Cardio 2: Demo - Day 7
  1. Array.prototype.some(); is there at least one match? Returns true or false.
  2. Array.prototype.every(); every single item in array matches to the condition or not? Returns true or false.
  3. console.log({variable}); - in console can be seen like
    
    isAdult:true
    
  4. Array.prototype.find(); Find is like filter, but instead returns just the one you are looking for
  5. With all these methods we can use array method without if-statment— because method returns true or false. So, instead this:
    const comment = comments.find(function(comment){
          if (comment.id === 823423){
             return true;
          }
    
        });
    
    we can write:
    const comment = comments.find(comment => comment.id ===823423);
    
  6. Deleting from array: First use Array.prototype.findIndex() and then use splice()
     const commentB = comments.findIndex(comment=>comment.id ===823423);
     //returns 1
    comments.splice(0, 1);
    
    or creating new array, spread and slice(),
    const index = comments.findIndex(comment=>comment.id ===542328);
        const newComments = [
          ...comments.slice(0,index),
          ...comments.slice(index + 1)
        ];
        console.table(newComments);
    
Day 7 code on github.

JavaScript30—Day 15

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 15 — LocalStorage and EventDelegation: Demo - Day 15
  1. Form and submit: if it is form you should listen to submit—event and not click.
  2. this.querySelector('[name=item]') So if we have form like this:
    We can grab input value like this:
    var input = document.querySelector('.js-it');
    var inputValue = input.value;
    
    or using this and parthensis:
    var input = (this.querySelector['name=it']).value;
    
  3. plates=[]: We have function
    function populateList(plates=[], plateList){
     //code here
        
      }
    
    
    plates=[] is an empty object and if we forget to pass something in, it won't broke our JavaScript
  4. .map(): creates from one array another array.
  5. .join(''): returns .map() array as a string.
  6. will still be checkedany existence of attribute checked will check it.
  7. localStorage accepts only strings. If it's something else in Console->Application-> Local Storage you'll see [object Object]. It can be stringified:
    localStorage.setItem('items', JSON.stringify(items));
    
  8. JSON. parse() is opposite to JSON.stringify(), itparses string to origin value or object.
  9. setting value as condition:
    const items = JSON.parse(localStorage.getItem('items')) || [];
    
Day 15 code on github.

JavaScript30—Day 28

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Sorting band names without a/an/the Lessons from Day 28 — Video Speed Scrubber: Demo - Day 28
  1. This tutorial won't work with YouTube videos because you can't put embeded video into video-tag.
  2. video-tag won't play .avi-format
  3. e.pageY : MouseEvent interface returns the Y (vertical) coordinatein pixels of the event relative to the whole document
  4. element.offsetTop: is the number of pixels from the top of the closest relatively positioned parent element.
  5. element.offsetHeight: is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar (if present, if rendered).
  6. HTMLMediaElement.playbackRate: property sets the rate at which the media is being played back. A value of 1.0 indicates normal speed and if negative—it's played back backwards. If it's too fast or slow— audio is muted.
Day 28 code on github.

JavaScript30 – Day 17

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Sorting band names without a/an/the Lessons from Day 17 — a/an/the: Demo - Day 17
  1. Regex to replace a/an/the with ' '
    function strip(bandName){
    
      return bandName.replace(/^(a |the |an )/i,'').trim();
    
    }
    
  2. Ternary operator - ?: is called ternary operator
    return strip(a) > strip(b) ? 1 : -1
    
  3. How to write a function in three ways:
    //first
    const sortedBands = bands.sort(function(a,b){
     return strip(a) > strip(b) ? 1 : -1
    });
    
    //as arrow-function
    const sortedBands = bands.sort ((a,b) =>{
     return strip(a) > strip(b) ? 1 : -1
    });
    
    // if the only thing you are doing in function is returning - you can do implicit return
    const sortedBands = bands.sort((a,b) => strip(a) > strip(b) ? 1 : -1);
    
  4. Output with/without commas
    sortedBands.map(band => `
  5. ${band}
  6. `); //will give you commas after the names: ["
  7. Anywhere But Here
  8. ", "
  9. The Bled
  10. ", "
  11. Counterparts
  12. ", "
  13. The Devil Wears Prada
  14. ", "
  15. The Midway State
  16. ", "
  17. Norma Jean
  18. ", "
  19. Oh, Sleeper
  20. ", "
  21. An Old Dog
  22. ", "
  23. Pierce the Veil
  24. ", "
  25. The Plot in You
  26. ", "
  27. Say Anything
  28. ", "
  29. A Skylit Drive
  30. ", "
  31. We Came as Romans
  32. "]
    sortedBands.map(band => `
  33. ${band}
  34. `).join(''); //will give
  35. Anywhere But Here
  36. The Bled
  37. Counterparts
  38. The Devil Wears Prada
  39. The Midway State
  40. Norma Jean
  41. Oh, Sleeper
  42. An Old Dog
  43. Pierce the Veil
  44. The Plot in You
  45. Say Anything
  46. A Skylit Drive
  47. We Came as Romans
Day 17 code on github.

JavaScript30 – Day 9

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 9: Demo - Day 9 Some console tricks (on Win Ctrl+Shift+I)
  1. Interpolated strings in console.log()
        console.log('Hello');
        console.log('I am a %s string', 'awesome' );
        var string = "awesome";
        console.log(`I am ${string} string`);
    
    
    Interpolated string
  2. Styling console.log()
        console.log('%c I am awesome string', 'color:#BADA55; font-size:20px;');
    
    Styled console.log()
  3. Warning—console.warn()
        console.warn("No!");
    
    consol. warn()
  4. Error—console.error()
        console.error("Smth went wrong!");
    
    console_error
  5. Info—console.info()
     console.info("console.info() is for providing info!");
    
    console_info
  6. Clearing console—console.clear()— simpliest way to clear console.
  7. Testing—console.assert() - returns only if the statemeny is false
        console.assert (1===1, 'That is true'); // won't show anything
        console.assert (1===2, 'That is wrong'); //shows text
    
        const p = document.querySelector('p');
        console.assert (p.classList.contains('whatever'), 'No such class!');
    
    console_assert
  8. Viewing DOM elements—console.dir
     console.log(p); //shows actual element itself
     console.dir(p); // shows all the element's attributes and methods
    
    Image shows only a fragment of console.dir(): console.dir()
  9. Grouping together—console.group()—uncollapsed version
    dogs.forEach(dog => {
          console.group(`${dog.name}`); // uncollapsed
          console.log(`This dog is ${dog.age} years old`);
          console.groupEnd(`${dog.name}`); // important to put otherwise inside each other
    
        });
    
    console_group_uncollapsed
  10. Grouping together—console.group()—collapsed version
    dogs.forEach(dog => {
          console.groupCollapsed(`${dog.name}`); // collapsed
           console.log(`This dog is ${dog.age} years old`);
          console.groupEnd(`${dog.name}`); // important to put otherwise inside eacother
    
        });
    
    Hugo is clicked open to show provided information: console_group_collapsed
  11. Counting—console.count()
        console.count('S');
        console.count('S');
        console.count('R');
        console.count('S');
        console.count('S');
        console.count('T');
        console.count('T');
        console.count('S');
        console.count('L');
    
    console_count
  12. Timing—console.time()— how long operation takes time
    console.time('fetching data');
        fetch('https://api.github.com/users/wesbos')
        .then(data => data.json())
        .then(data =>{
          console.timeEnd('fetcing data');
          console.log(data);
        });
    
    console_time
  13. console.table()—displays tabular data as table
    console.log(dogs);
    console.table(dogs);//same size of objects
    
    console_table
Day 9 code on github.

JavaScript30 – Day 10

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 10: Demo - Day 10
  1. let var - another type of variable in JavaScript. Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks . In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing functionMDN link
  2. inBetween = !inBetween is same as inbetween = true. It's also called a flag variable - a flag variable, in its simplest form, is a variable you define to have one value until some condition is true, in which case you change the variable's value.
  3. Warning‐change vs click I started it by myself and in this point - it didn't react anyhow.
    if(e.shiftKey && this.checked){
    	console.log("jep");
    }
    
    
    As I listened to the 'change', I changed it to 'click' and voila - it worked.
Day 10 code on github.

JavaScript30 – Day 8

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 8: Demo - Day 8
  1. Organizing your variables and values as an array:
    [lastX, lastY] = [e.offsetX, e.offsetY];
    
    is the same as:
    lastX = e.offsetX;
    lastY = e.offsetY;
    
  2. hsl— h is for hue (between 0-360), s is for saturation and l is for lightness.
  3. strokeStyle and lineWidth It's ctx.strokeStyle for color, but ctx.lineWidth for width.
  4. direction != direction and direction = !direction - let's assume that direction is true:
    direction != direction // true isn't equal to true
    direction = !direction  // change direction's value to opposite - if true, now be false
    
    
  5. Debugging:
    • console.log(canvas)- as it didn't do anything and no spelling mistakes so far - turned out I had accidentally deleted the -tag.
    • inside draw() - console.log(e) after the condition, if I console it before it gives me true and false, but I only want one of them.
    • calling out draw function - addEventListener('mousemove') worked but nothing else didn't care if it was false or true. Possible ways to debug:
      inside function draw(){
      	console.log(isDrawing);
      	if(isDrawing ="false") return;
      }
      
      It turned out to be spelling mistake in addEventListener('mousedown'),()=> isDARwing = true); and not addEventListener('mousedown'),()=> isDRAwing = true);
Day 8 code on github.

JavaScript30 – Day 1

JavaScript30 is 30-day vanilla javaScript coding challenge by Wes Bos (@wesbos). Actually I saw this challenge at the beginning of the year and thought "no, won't take it because probably I won't finish it" ... but here I am. I'm still not sure about finishing, but if I can get it through till the end of the year - well done! The purpose of these posts is to reflect my troubles and moments of ahhaa. Lessons from Day 1: Demo - Day 1
  1. const– so far I've used only var to define variables. Const values cannot be changed or redeclared.
  2. ` back-ticks and template literals:
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    
    This is the part I struggled the most. If I copied it, it worked, if wrote it on my own– it didn't. And I couldn't understand why? And no ideas what to google for. Fortunately there is always Twitter. Yes, I know there are different types of quotes - ",',´. But turns out there are also backticks - on Win you can type them ALT + (num keyboard on right) 9+ (num keyboard on right) 6 or you have to Google for which key to press. `${variable}` as templating literals allowing embedded variables.
  3. http://keycode.info/ to find quickly keyboard's key code.
  4. if(!Obj) return; – stop the function if the Obj is null (there is no such object). I think I'm familiar with the concept but why I haven't it used before?
  5. arrow-function So this function:
     allAs.forEach(function(element) {
                 element.classList.add('playing');
            });  
    
    
    can be written as an arrow-function:
     allAs.forEach(element => element.classList.add('playing'));
    
  6. <kbd> is html—tag for keyboard input
  7. Adding audio files I had to add .mp3 to the end.
    	
    
  8. As I changed the word to "javascript" I had two "A"s. It got me some time to figure out that I can't detect if it is the first A or the second one by keypress. So, I had to modify my code: a) check if it is A b) if it is get all the A-s (document.querySelectorAll) c) and each of them add class "playing"
     if(e.keyCode =="65"){
             // get all letter A                 
             allAs = document.querySelectorAll(`div[data-key="${e.keyCode}"]`);
             allAs.forEach(element => element.classList.add('playing'));
             
        } else {
           key.classList.add('playing');
        }
    
    
Day 1 code on github.