zoom on some HTML tags

August 6, 2023 Reading time: 11 minutes

I'm taking w3schools HTML course as a refresher and I learned a few things along the way.

quotations

I knew about blockquote but not sure about the other two.

Quote from another source:

  • use blockquote tag with cite attribute containing URL to the source
  • browser behaviour: usually indent

Short inline quote:

  • use q tag
  • browser behaviour: usually add quotation mark

Indicate the title of a work:

  • use cite tag
  • browser behaviour: usually render in italic

td

td stands for table data! th (table header) and tr (table row) were clear to me but I always wondered why a table cell was written "td". Now I can properly read the code in my head haha

image size

In the img tag, prefer using style attribute with width and height properties inside rather than width and height attributes. style attribute takes precedence over the style defined in the linked CSS file (for instance max-width: 100%;) or at the HTML page level, but width and height attributes come second.

W3Schools recommends to always specify the width and height of an image. If not, the web page might flicker while the image loads.

picture

This element is new to me. Inside you can define a list of images to display acording to the screen size, so to save bandwith and cover different format supporting from the browsers. It should always ends with an img tag. For instance (from W3Schools):

<picture>
  <source media="(min-width: 650px)" srcset="img_food.jpg">
  <source media="(min-width: 465px)" srcset="img_car.jpg">
  <img src="img_girl.jpg" style="width:auto;">
</picture>

lists

Can't always remember of dl (description list) with dt (term) and a dd (description), so now it's somewhere on this blog.

Also, it's good to now that there's a type attribute for ordered list (ol) to specify the type of the list item marker:

  • type="1" for number marker (default)
  • type="A" for uppercase letter marker
  • type="a" for lowercase letter marker
  • type="I" for uppercase roman number marker
  • type="i" for lowercase roman number marker

As well as a start attribute to chose from which number to start.

iframe

iframe stand for inline frame. It is used to embed another document in current document (just like a Youtube video for instance). Don't forget title attribute for screen readers. Default display will add borders so make sure you remove them with CSS or style attribute.

An iframe can be the target of a link, just refer to it with it's name: (example from W3Schools):

<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>
<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

noscript

Don't forget to let the user know JavaScript is needed for this or this functionnality with noscript tag:

<noscript>Sorry but the game relies on JavaScript. Have a look at your browser's settings if you wish to play it.</noscript>

list of semantic elements and definition

From W3Schools.

  • article -> defines an independent, self-contained content
  • details -> defines additional details that the user can open and close on demand
  • summary -> defines a heading for the details element
  • figcaption -> defines a caption for a <figure> element. The <figcaption> element can be placed as the first or as the last child of a <figure> element.
  • figure -> defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
  • img -> defines the actual image/illustration
  • mark -> defines marked/highlighted text
  • time -> defines a date/time

Landmarks

Landmarks define some parts of the page to jump to with the help of a screen reader #accessibility

  • header -> defines a header for a document or a section
  • nav -> defines a set of navigation links
  • main -> defines the main content of a document. Should be unique.
  • aside -> defines content aside from the content (like a sidebar)
  • section -> defines a section in a document
  • footer -> defines a footer for a document or a section

A section can include article and an article section, depends of the content.

A header can be found in several zones in an HTML document except in a footer, address or header element.

A footer is also repeatable in the HTML document.

Note that a button element should be used for any interaction that performs an action on the current page. The a element should be used for any interaction that navigates to another view.

kbd

kbd stands for keyboard inuput. Default browser's display is monospace font.

Use lowercase for file names

Some web servers (Apache, Unix) are case sensitive about file names: "london.jpg" cannot be accessed as "London.jpg".

Other web servers (Microsoft, IIS) are not case sensitive: "london.jpg" can be accessed as "London.jpg".

time

Nesting time or duration information into a time element is useful for any automatic reading of a page, from a search engine for instance.

I'll be celebrating my birthday on <time datetime="2024-09-21T20:00">September 21<sup>st</sup></time> for <time datetime="PT2H30M">2h30m</time>.

Bootstrap at a glance

July 28, 2023 Reading time: 10 minutes

What

A free CSS framework to work with when time supply is running low.

Version 3 is the most stable version, supported by all modern browsers.

How

Bootstrap is a combination of pre-written CSS and JavaScript (jQuery) files, both available from a CDN. To access it, add reference to head element:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

Where

Some code snippets are available on my dedicated CodePen

Basic structure

A section needs a container class

Encapsulate your section into a container class which can be either:

  • container (fixed width container) OR
  • container-fluid (full width container)

A section is 12 columns-wide

Group elements in a row with row class then distribute included elements into columns per screen size with col-screenSize-numberOfColumns class. An additionnal well class would add grey background color and rounded border to the zone.

size would be:

  • xs for phones - screens less than 768px wide / extra-small
  • sm for tablets - screens equal to or greater than 768px wide / small
  • md for small laptops - screens equal to or greater than 992px wide / medium
  • lg for laptops and desktops - screens equal to or greater than 1200px wide / large

numberOfColumns is a number between 1 and 12. A row should have a total of 12 colums for each screenSize.

For instance, if we want to align 3 buttons in a row, it means 1 button should be 4 colums wide (3 * 4 = 12).

<div class="row">
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>1</button>
 </div>
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>2</button>
 </div>
<div class="col-xs-4 col-md-4 col-lg-4 well">
  <button>3</button>
 </div>
</div>

Navbar

Add a static navbar to the top of the page with your website's name, dropdowns, collapsable for small screens, align sign in button to the right and so on. Have a look on CodePen.

Basic classes

Contextual Colors and Backgrounds

Classes for colors are:

  • element-muted
  • element-primary
  • element-success
  • element-info
  • element-warning
  • element-danger

element could be text, bg, alert, btn

Image and image gallery

Some useful class for img element:

  • img-thumbnail: adds some rounded borders and padding
  • img-responsive: applies display: block, max-width: 100% and height: auto.

To create a gallery, combine thumbnail class with Bootstrap grid system:

  • create an element with container class
  • within the container, create as many elements with row class as you need
  • within each row, divide the space into as many colums as you need (col-screenSize-numberOfColumns)
  • within each colum, apply thumbnail class to a wrapper element such as figure that will contain a link to the image source full size that will itself contain
    • the image element
    • a figcaption element

Create an 'alert' element

Show the user some confirmation or alert message within an element, such as a div. Apply alert class to an element in addition with a alert-contextualColor class (see above) and alert-dismissible class to allow user to remove the element. Removal can be smoothened with fade and in classes. For instance:

<div class="alert alert-success alert-dismissible fade in">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  <strong>Success!</strong> Indicates a successful or positive action.
</div>

Customize button, a, input

Basic classes to apply on a button, a or input elements are:

  • btn and
  • btn-default (display as wide as the text it contains) OR
  • btn-block (as wide as 100% of the available width (breaks on a new line))

Then add if needed:

  • color: btn-contextualColor
  • size: btn-size

a & button groups

A collection of share links can typically be grouped on a single line with btn-group or btn-group-vertical (+ -size if needed) applied on wrapper element.


functions

April 13, 2023 Reading time: 4 minutes

Dividing the code into functions is essential.

Basically, a function can take an input (from zero to several parameters - a parameter can be a function) and provide a result whenever it's called.

In JavaScript, a function is a value.

Named function

Declaration

A declared function is visible in the whole script.

function sayHello() {
console.log("hello")
}

The function name is usually a verb briefly describing the action. One function should do one action. Here's how to call it:

sayHello() // consols "hello"

Return

When reached, the return keyword makes the function stop and returns the results if any (default return value is undefined)

function checkAge(age) {  return age >= 18 ? true : false;}
checkAge(18) // returns true
checkAge(10) // returns false

A function can update variables without returning anything. For instance (from FreeCodeCamp) :

let sum = 0;

function addSum(num) {
  sum = sum + num;
}

addSum(3); // sum variable now equals 3
console.log(addSum(3)) // returns undefined

Default parameter value

Consider this function expecting three parameters:

function add(a, b, c) {  
return a + b + c
}

If a parameter is not passed on, it's value is considered as undefined.

add(4, 2) // returns NaN (Not a Number)

You can specify a default value if the parameter is omitted:

function addition(a, b, c = 0) {  
return a + b + c
}
add(4, 2) // returns 6

Rest parameter

The rest parameter (...param) is useful if we want a function to work with a variable number of arguments. Arguments passed this way are stored as an array. Check out this example:

function howMany(...args) {
  return args.length;
}
console.log(howMany(0, 1, 2)); // returns 3
console.log(howMany("string", null, [1, 2, 3], { })); // returns 4

Anonymous function

Anonymous or expressed functions are useful when we don't need to re-use them anywhere else in the code. It exists once it's reached. Here are two use-cases with possible syntax:

Calculate a value and pass it to a variable

Examples from FreeCodeCamp:

const myFunc = function() {
  const myVar = "value";
  return myVar;
}

With ES6 it can be shortened into an arrow function:

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

Note that if we only want a value to be returned, then "return" keyword as well as brackets surrounding the code can be omitted.

const myFunc = () => "value";

If we need to pass arguments, the same principle as for named functions applies, except than parenthesis enclosing the parameter can be omitted if there's only one parameter:

const doubler = item => item * 2;
doubler(4);

const multiplier = (item, multi) => item * multi;
multiplier(4, 2);

Create an objet

Consider this object literal declaration (from FreeCodeCamp) which returns an object containing two properties:

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

Since ES6 a syntactic sugar exists. It eliminates the redundancy:

const getMousePosition = (x, y) => ({ x, y });

Here, x will be converted to x: x.



regex

March 15, 2023 Reading time: 11 minutes

These past few weeks I learned about regular expressions. Here's a recap! Almost all examples come from FreeCodeCamp.

Methods

Test method

let stringToTest = "a string";
let regEx = /pattern/;
regEx.test(stringToTest); // returns false

returns true or false depending if the pattern is found or not

Match method

let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex); // returns ["expressions"]

returns an extraction of the string that matches the provided pattern.

Replace method

let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue"); // returns "The sky is blue"

searches for the described pattern and replacing it by a value of your choice.

You can also access capture groups in the replacement string with dollar signs ($) (see group capture in Patterns/Group elements/Reuse group).

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); // returns "Camp Code"

Positive and negative lookahead

This is actually not a method but a special pattern to look ahead in the string for patterns further along. It won't match the element.

Use (?=...) to verify the element ("...") is there

Use (?!=...) to verify the element ("...") is not there

let quit = "qu";
let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex); // returns ["q"] ("u" is there)
noquit.match(qRegex); // returns ["q"] ("u" is not there)

Greedy vs lazy matching

This is not a method either but note that regular expressions are by default greedy meaning they will find the longest possible part of a string that fits the regex pattern and returns it as a match.

let string = "titanic";
let regEx = /t[a-z]*i/;
string.match(regEx); // returns "titani"

You can use ? to change it to lazy matching meaning the regular expression will find the shortest possible part of the string.

let string = "titanic";
let regEx = /t[a-z]*?i/;
string.match(regEx); // returns "ti"

Flags

Append flag right after the end of a pattern (//) if you need to extend the search to the whole string and/or ignore letter case.

Global search

Use g flag to search or extract a pattern more than once.

let testStr = "Repeat, Repeat, Repeat";
let repeatRegex = /Repeat/g;
testStr.match(ourRegex); // returns ["Repeat", "Repeat", "Repeat"]

Ignore case

Use i flag to ignore letter case (ie the difference between uppercase and lowercase letters).

let repeatRegex = /ignorecase/i;

This regex can match the strings ignorecase, igNoreCase, and IgnoreCase.

Multiple flags

Just concatenate them, for instance

let regEx = /search/gi

Patterns

Define a character set (aka character class)

Define a character set between square brackets []

Inside, define a list of character or a range of characters, using a hyphen character - to seperate from and to elements. Letters and numbers can be combined.

let regEx1 = /aeiu/
let regEx2 = /[a-e]/
let regEx3 = /[3-9]/
let regEx4 = /[a-e3-9]/

let catStr = "cat";
let batStr = "bat";
let matStr = "mat";
let bgRegex = /[a-e]at/;
catStr.match(bgRegex); // returns ["cat"]
batStr.match(bgRegex); // returns ["bat"]
matStr.match(bgRegex); // returns null

Negate a character set

Add ^ at the beginning of the character set you want to negate

let regEx = /[^aeiou]/gi // matches everything that is not a vowel

Group elements

Use () to group elements

let testStr = "Pumpkin";
let testRegex = /P(engu|umpk)in/;
testRegex.test(testStr); // Returns true

Reuse group

A group is saved as a temporary "variable" that can be accessed within the same regex using a backlash and the number of the captured group (e.g. \1). The number corresponds to the position of their opening parentheses, starting at 1.

let repeatStr = "row row row your boat";
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]

Possible existence of an element

Use ? right after the element

let american = "color";
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true

Alternative element

Use | (OR operator) between each element

let regEx = /yes|no/

Any element

Use wildcard character . to match any one character

let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr); // returns true
huRegex.test(hugStr); // returns true

Litteral string

Type the string you're looking for between / and /

let testStr = "Hello, my name is Kevin.";
let testRegex = /Kevin/;
testRegex.test(testStr); // returns true

All letters, numbers and underscore

Use \w

let longHand = /[A-Za-z0-9_]+/;
let shortHand = /\w+/;

For everything but letters, numbers and underscore, use \W (short hand for [^A-Za-z0-9_])

All numbers

Use \d

let longHand = /[0-9]/;
let shortHand = /\d/;

For all non-numbers, use \D (short hand for [^0-9])

Whitespace characters

Use \s to look for whitespace, carriage return (\r), tab (\t), form feed (\f), new line (\n) and vertical tab (\v)

let longHand = /[\r\t\f\n\v]/;
let shortHand = /\s/;

For non-whitespace, use \S (shorthand for [^ \r\t\f\n\v])

Define beginning and/or end of a pattern

Beginning

Use ^ outside of a character set and at the beginning of the regex

let firstString = "Ricky is first and can be found.";
let notFirst = "You can't find Ricky now.";
let firstRegex = /^Ricky/;
firstRegex.test(firstString); // returns true
firstRegex.test(notFirst); // returns false

Ending

Use $ at the end of the regex

let theEnding = "This is a never ending story";
let storyRegex = /story$/;
storyRegex.test(theEnding); // returns true
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding); // returns false

Occurencies

One or more times

Use + right after the character than can be found one or more times

let string1 = "abc"
let string2 = "aabc"
let string3 = "abab"
let regEx = /a+/g
string1.match(regEx); // returns [ 'a' ]
string2.match(regEx); // returns [ 'aa' ]
string3.match(regEx); // returns [ 'a', 'a' ]

Zero or more times

Use * right after the character that can be found zero or more times

let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // returns ["goooooooo"]
gPhrase.match(goRegex); // returns ["g"]
oPhrase.match(goRegex); // returns null

Number of matches

Exact number

Specify a certain number of patterns using curly bracket {}

let A4 = "haaaah";
let A3 = "haaah";
let A100 = "h" + "a".repeat(100) + "h";
let multipleHA = /ha{3}h/;
multipleHA.test(A4); // returns false
multipleHA.test(A3); // returns true
multipleHA.test(A100); // returns false

Lower number

To only specify the lower number of patterns, keep the first number followed by a comma.

let A4 = "haaaah";
let A2 = "haah";
let A100 = "h" + "a".repeat(100) + "h";
let multipleA = /ha{3,}h/;
multipleA.test(A4); // returns true
multipleA.test(A2); // returns false
multipleA.test(A100); // returns true

Lower and upper number

Put two numbers between the curly brackets, separated by a comma - for the lower and upper number of patterns.

let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // returns true
multipleA.test(A2); // returns false

objects

February 25, 2023 Reading time: 8 minutes

Let's continue our exploration of data sets in JavaScript by having a look at the objects!

Store

An object is also a collection of data but in a structured way as it's stored by pairs of property (or key) / value. For instance:

const BOOK = {
title: "The Lord of the Rings",
  "volumes": 3,
"main characters": ["Frodo", "Aragorn"],
9: ["Fellows", "Nazgul"]
};

Notes:

  • properties can be strings or numbers. Here's their syntax:
    • single word (title, volumes): quotes can be omitted (JavaScript will automatically typecast them as strings if the object has any non-string properties)
    • several words ("main characters"): quotes must be added
    • numbers (9): just type the number
  • as values, an object can contain strings, numbers, booleans, arrays, functions, and objects.

Access

Via dot or bracket notation

To access the propertie's value, you can either use the dot or the bracket notation:

const TITLE = BOOK.title;
const VOLUMES = BOOK["volumes"];
const MAIN_CHARACTERS = BOOK["main characters"];
const NINE = BOOK[9]

You can use the dot notation if your property in a string of a single word. Otherwise, user the bracket notation with quotes for strings and without for numbers.

Via a variable

Properties stored as value of a variable can also be access with the bracket notation. For instance:

const MAIN_CHARACTERS = "main characters";
let charactersList = BOOK[MAIN_CHARACTERS];
console.log(charactersList);

will print

[ 'Frodo', 'Aragorn' ]

on the console.

This can be very useful for iterating through an object's properties.

Nested objects

The same principle applies to access to sub propertie's values, just continue to filter via bracket or dot notation until you reach your destination. For instance (from FreeCodeCamp):

const ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};

ourStorage.cabinet["top drawer"].folder2; // returns string "secrets"
ourStorage.desk.drawer; // returns string "stapler"

Does this property exist?

To check if the property of a given object exists or not, use the .hasOwnProperty(propname) method. It returns true or false if the property is found or not. For instance:

BOOK.hasOwnProperty("title"); 
BOOK.hasOwnProperty("author");

The first hasOwnProperty returns true, while the second returns false.

Note: always use quotes for string properties, otherwise an error is thrown.

Extract

Generate an array of all object keys

Use Object.keys() method. It takes an object as the argument and returns an array of strings representing each property in the object. The order is first all non-negative integer keys in ascending order by value, then other string keys in ascending chronological order of property creation. For instance:

Object.keys(BOOK) // returns [ '9', 'title', 'volumes', 'main characters' ]

Generate an array of all object values

Same principle. Use Object.values() method.

Object.values(BOOK) // returns [ [ 'Fellows', 'Nazgul' ], 'The Lord of the Rings', 3, [ 'Frodo', 'Aragorn' ] ]

Generate an array of all object key/value pairs

Same principle. Use Object.entries() method.

Object.entries(BOOK) //returns [ [ '9', [ 'Fellows', 'Nazgul' ] ], [ 'title', 'The Lord of the Rings' ], [ 'volumes', 3 ], [ 'main characters', [ 'Frodo', 'Aragorn' ] ] ]

Iterate through

Use a for...in statement. It looks like this:

for (let item in BOOK) {
  console.log(item);
} // logs 9, title, volumes, main characters, each value in its own line

Here, "item" is a variable we define - it could be any name. Its value will change at each iteration.

Use destructuring assignment

The example comes from FreeCodeCamp.

Consider this object:

const user = { name: 'John Doe', age: 34 };

To extract both values and assign them to variables you could use:

const { name, age } = user; 

Read it as: "create constants named "name" and "age" containing values from "name" and "age" properties in "user" object". This is a shorthand equivalent of

const name = user.name;
const age = user.age;

A console.log on name and age would return John Doe and 34, each on its own line

Manipulate

Prevent mutation

const declaration can by bypassed. To protect data from mutation, use Object.freeze() function. The argument would be the object you'd like to freeze. For instance (from FreeCodeCamp):

let obj = {
  name:"FreeCodeCamp",
  review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad";
obj.newProp = "Test";

obj.review and obj.newProp assignments will result in errors and the object wouldn't change.

Update or add a value

Proceed like any other variable; using dot or bracket notation. For instance:

BOOK["main characters"][1] = "Sam";
BOOK["main characters"][2] = "Bill";
console.log(BOOK["main characters"]);

will print

[ 'Frodo', 'Sam', 'Bill' ]

on the console.

Append a property

Proceed just like you would for updating. For instance:

BOOK.format = "";
BOOK["number of copies"] = 100;
BOOK[5] = "Hello";

BOOK object will now look like this:

{
'5': 'Hello', '9': [ 'Fellows', 'Nazgul' ], title: 'The Lord of the Rings', volumes: 3, 'main characters': [ 'Frodo', 'Aragorn' ],
format: '', 'number of copies': 100
}

Order has not much importance from an object perspective because you're not using indexes to access data. But if this is important, consider using the spread operator (I'll probably write a blog entry later on this subject). Note that number properties order themselves at the beginning of the object.

Delete a property

User the delete keyword and then target your property according to it's format. For instance:

delete BOOK.format;
delete BOOK["number of copies"];
delete BOOK[5];

create or update project on GitHub

February 19, 2023 Reading time: 3 minutes

This is a personal step by step procedure to be updated.

Create (via command lines)

  1. open a terminal

  2. get the path to your project folder stored on your device

  3. write cd (for change directory) and then the path. For instance:
    cd Documents/www/project
  4. initialize the repository
    git init
  5. push all files (.) from this /project folder into staging (wait line)
    git add .
  6. push the package from staging to local repository and provide a message into quotes
    git commit -m "initial commit"
  7. create distant repository on GitHub (New repository) and copy the URL (https://github.com/username/project.git)

  8. push the package from local repository to distant repository

    1. indicate which repository you are aiming (replace "URL" by the one you copied on step 7)
      git remote add origin URL
    2. push it
      git push -u origin master
    3. enter your username and token

  9. verify result on GitHub

Update

via Code - OSS

via Command lines

  1. open a terminal

  2. get:
  3. write cd (for change directory) and then the path. For instance:
    cd Documents/www/project
  4. push all files (.) from this /project folder into staging (wait line)
    git add .
  5. push the package from staging to local repository and provide a message into quotes
    git commit -m "changed this"
  6. push the package from local repository to distant repository

    1. indicate which repository you are aiming (replace "URL" by the one you copied on step 2). Branch "master" and URL are optional
      git remote add master URL
    2. push it. Branch "master" is optional
      git push -u master
    3. enter your username and token

  7. verify result on GitHub