arrays

February 7, 2023 Reading time: 9 minutes

I learned a few things about JavaScript on OpenClassrooms (taking Apprenez à programmer avec JavaScript Écrivez du JavaScript pour le web courses). I didn't know it then but I was actually looking for DOM manipulation for my Qwixx project. Anyway, I'm refreshing my newbie knowledge by taking FreeCodeCamp JavaScript Algorithms and Data Structures course and here is a recap about arrays.

Store

An array can store multiple pieces of data in a single variable. Each entry is separated by a comma and nested into square brackets. Just like this:

const SANDWICH = ["peanut butter", 1, true, ["bakery", "home-made"]];

An array containing another array is also called a multi-dimensional array. An array can also contain objects.

Access

"peanut butter" 1 true ["bakery", "home-made"]
0 1 2 3

Arrays use zero-based indexing, so the first element in an array has an index of 0. Use square bracket notation to get the data associated to the index. For instance:

console.log(SANDWICH[0]);
const EATEN = SANDWICH[1];
console.log(EATEN);

will print "peanut butter" string and 1 number.

Note that additional pair of brackets refers to the next level of entries inside.

const BOUGHT_IN = SANDWICH[3][0];
console.log(BOUGHT_IN);

will print "bakery".

Check for the presence of an element

Use indexOf() method. It returns -1 if the item is not found. For instance:

SANDWICH.indexOf('peanut butter'); // returns 0 
SANDWICH.indexOf('butter'); // returns -1

Call for all items of an array

Use spread operator (...). For instance (from FreeCodeCamp):

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // maximus has the value of 89

Iterate through

Use a for loop. It looks like this:

let array = [1, 2, 3]
for (let i = 0; i < array.length; i++) {
console.log(array[i])
} // logs 1, 2, 3, each on its own line

Manipulate

Update data

Even if an array is defined as a const its entries are mutable. From our example,

SANDWICH[0] = "houmus";

SANDWICH now has the value

["houmus", 1, true, ["bakery", "home-made"]];

Append data

Onto the end of an array

Use push() method. It takes one or more parameters and "pushes" them onto the end of an array. For instance:

const arr = [1, 2, 3];
arr.push(4);

arr now has the value [1, 2, 3, 4]

Onto the beginning of an array

Use unshift() method. For instance:

const arr = [1, 2, 3];
arr.unshift(0);

arr now has the value [0, 1, 2, 3]

Somewhere specific

Use splice() method.

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted
Third argument (optional): items to insert starting at that same index, searated by a comma

For instance (example from FreeCodeCamp):

const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers); // returns [ 10, 11, 12, 13, 14, 15 ]

Append elements from another array

User spread operator (...). For instance (example from FreeCodeCamp):

let arrayToAppend = ['sage', 'rosemary', 'parsley', 'thyme'];
let mainArray = ['basil', 'cilantro', ...arrayToAppend, 'coriander'];

mainArray now has the value ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']

Remove data

From the end of an array

Use pop() method. For instance:

const arr = [1, 2, 3];
arr.pop();

arr now has the value [1, 2]

From the beginning of an array

Use shift() method. For instance:

const arr = [1, 2, 3];
arr.shift();

arr now has the value [2, 3]

Note: removed data can be returned if assigned to a variable. For instance:

const arr = [1, 2, 3];
let removedNumber = arr.pop();
let one = arr.shift();

removedNumber has the number 3 as a value and one, 1

Somewhere specific

You can also use splice() method!

First argument: the index at which to begin deleting elements
Second argument (optional):  the number of elements to be deleted

For instance (from FreeCodeCamp):

let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2); // array now has the value ['today', 'was', 'great']

Here we remove 2 elements, beginning with the third element (at index 2). array would have the value

Note: removed data can be returned if assigned to a variable.

Copy an array

I realized it was not working like classic variables like these:

let a = "first variable"; // a contains "first variable" string
let b = a; // a and b contain "first variable" string
b = "second variable"; // a contains "first variable" and b "second variable" string

let array1 = [1, 2, 3]; // array1 contains [1, 2, 3] array
let array2 = array1; // array1 and array2 contain [1, 2, 3] array
array2.unshift(0); // array1 and array2 contain [0, 1, 2, 3] array

Here, array2 behaves just like another pointer to the same object. Modifying array2 will modify array1 and inversely. So how can we copy an array? Here are several methods:

With spread operator

For instance:

let originalArray = ['great', 'awesome', 'super', 'wonderful'];
let copiedArray = [...originalArray];

originalArray remains unchanged and copiedArray has the same elements as originalArray.

With slice() method

With slice() method, we can copy or extract a given number of elements to a new array, leaving the original array unchanged. It takes 2 parameters:

First argument: the index at which to begin extraction
Second argument (optional):  the index at which to stop extraction (not included)

For instance (example from FreeCodeCamp):

let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3); // todaysWeather is ['snow', 'sleet']

Are you inline or block?

January 20, 2023 Reading time: 5 minutes

Again, this article has to do with understanding default display value before attempting changes. An HTML element could be either inline or block.

Inline element

  • Takes up content's width
  • Cannot contain a block element

Most used inline elements: a, img, br, span, input, label

Often used inline elements: button, code, em, strong, textarea, select

Block element

  • Starts on a new line and takes up full width of their parent element
  • Browser adds default margin

Most used block elements:

  • semantical structure (header, nav, main, section, article, p, aside, footer) + div
  • table (table, tfoot)
  • lists (ul, li, ol)
  • form (form, fieldset)
  • heading (h1 to h6)

Change default display

Diplay can be decomposed in two directions: outer (element's participation in flow layout) and inner (sets layout of children).

Use display property and set it to block or inline - this defines outer direction

Depending on your intent, you may also want to consider using flex value to manage the inner direction

Note that you can use precomposed values containing both outer and then inner instructions such as inline-flex or inline-block.

Zoom on inline-block

Using inline-block you can transform a block element into an inline element, with a width set. Just remember that your two elements must be on the same line to fit into a 100% width. Use a wrapper to set space between elements. Full demo can be found on CodePen. In the following example, p elements will be displayed side by side.

CSS

p { 
display: inline-block;
width: 50%;
}

HTML

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec neque ut dolor vehicula malesuada.</p><p>Aliquam ornare, orci elementum gravida congue, augue eros congue diam, nec vehicula velit velit non 
orci. In eget sem nunc. Nulla facilisi.</p>

forms forms forms

January 9, 2023 Reading time: 24 minutes

Forms are inevitable on a web journey. Here are some commented examples to understand each component

Table of contents:

search field form

<form action="/search" role="search">
<label for="search-input">Search articles</label>
<input type="search" id="search-input" placeholder="Search…" name="q" />
<input type="submit" value="Submit search" />
</form>

Let's take this search field form (from How to transfigure wireframes into HTML by Lara Aigmüller) as an example.

form tag -> to open an area in the document where the user can provide information
action attribute -> indicates an URL where the form data should be sent. If omitted, it defaults to current page.
role attribute -> for accessibility purposes (value is search to identify search functionnality)

label tag -> to help associate the text for an input element with the input element itself (clicking on the text will select the corresponding button; helpful for assistive technologies)
for attribute -> association method with an input id where values are the same. Another method could be:

<label>
<input type="search" id="search-input" placeholder="Search…" name="q" />
Search articles
</label>

input tag -> allows several ways to collect data
type attribute -> many possible values, see below
id attribute -> the most important attribute in the universe. Used to identify specific HTML elements. Each id attribute's value must be unique from all other id values for the entire page.
placeholder attribute -> used to give people a hint about what kind of information to enter into an input but this is actually not a best-practice for accessibility (users can confuse the placeholder text with an actual input value).
name attribute -> value to represent the data being submitted, mandatory to be processed on the server-side. Helps grouping radio buttons (selecting one deselects the other - see survey form example).
value attribute -> initial value (for submit and button types: text that will display) - for instance ->

Go back to Table of contents

contact form

<form method="post" action="./contact">
<input id="name" type="text" name="name" value="" placeholder="Name" required>
<input id="email" type="email" name="email" value="" placeholder="Email" required>
<textarea id="message" rows="6" name="message" placeholder="Message" required></textarea>
<div data-sitekey="..."></div>
<button id="submit" name="submit" type="submit">Send email</button>
</form>

Let's take this contact form (from Bludit plugin) as an example.

form tag method attribute -> specifies how to send form-data

  • as URL variables (method="get")
    • better for non-secure data, like query strings (appends form-data into the URL in name/value pairs)
    • limited lenght of the URL (2048 characters)
  • as HTTP post transaction (method="post")
    • appends form-data inside the body of the HTTP request (data is not shown in URL)
    • has no size limitations

input tag required attribute -> data is mandatory to allow submission

div tag data-sitekey attribute -> I'll do some research on this topic later on. For now let's just say it's used to prevent spaming using CAPTCHA.

Question of the day: is there a "better" solution between button and input tag when type is submit? After some research I believe the answer is: no, functionnaly, it's identical. However, button elements are much easier to style and inner HTML content can be added. Note however that the first input element with a type of submit is automatically set to submit its nearest parent form element.

Go back to Table of contents

survey form

This is an example from FreeCodeCamp Responsive Web Design course:

<form action="https://freecatphotoapp.com/submit-cat-photo" target="_blank"> 
<fieldset>
<legend>Is your cat an indoor or outdoor cat?</legend>
<label>
<input id="indoor" type="radio" name="indoor-outdoor" value="indoor" checked> Indoor
</label>
<label>
<input id="outdoor" type="radio" name="indoor-outdoor" value="outdoor"> Outdoor
</label>
</fieldset>
<fieldset>
<legend>What's your cat's personality?</legend>
<input id="loving" type="checkbox" name="personality" value="loving" checked>
<label for="loving">Loving</label>
<input id="lazy" type="checkbox" name="personality" value="lazy">
<label for="lazy">Lazy</label>
<input id="energetic" type="checkbox" name="personality" value="energetic">
<label for="energetic">Energetic</label>
</fieldset>
<input type="text" name="catphotourl" placeholder="cat photo URL" required>
<button type="submit">Submit</button>
</form>

form tag, target attribute -> defines where to display the response after submitting the form. Default value is _self (ie current window)

fieldset tag -> used to group related inputs and labels together

legend tag -> acts as a caption for the content in the fieldset element

input tag
value atribute -> even if optionnal, it's best practice to include it with any checkboxes or radio buttons on the page. Otherwise, the form data would include name-value=on, which is not useful.
checked attribute -> force selection by default 

button tag type attribute submit value -> note this is the default if the attribute is not specified for buttons associated with a <form>, or if the attribute is an empty or invalid value. button tag should always have a type attribute because different browsers may use different default types.

Go back to Table of contents

input types

What type of input do you need?

Most common inputs types

  • no type equals text ie a one line text field of 20 characters
  • checkbox, radio - group with name attribute
  • email - has validation functionnalities included
  • password - one line text field where value is hidden - displays an alert if the site is not secured. Use the pattern attribute to define a regular expression that the password must match to be considered valid (for instance [a-z0-5]{8,} -> should match eight or more lowercase letters or the digits 0 to 5)
  • search

Special inputs types

  • color
  • time-related input types:
    • month (month, year)
    • date (day month year). Note you can use the min and max attributes to add restrictions to dates (for instance min="2000-01-02")
    • datetime-local (day month year hour minutes, local time)
    • week (week number)
    • time (hour minutes, local time)
  • file - to select a file. Use accept attribute to define what kind of files you may want
    <input type="file" accept="image/*,.pdf">
  • hidden - not displayed to users, can be used to transport additionnal information when the form is submitted. But do not use as a form of security because it is visible (and can be edited) using any browser's developer tools.
  • number - rejects non numerical values. Can use min and max attributes
  • range - displays an horizontal bar where exact value is not important (for instance: volume controller). Accepts min and max attributes
  • tel - to get a phone number
  • url - has validation parameters

Button inputs types

  • image - use src attribute for the image file and alt attribute in case it's missing
  • button - no particular behaviour defined. Displays value from value attribute if provided
    <input type="button" value="Let's play!">
  • submit - sends the form

Go back to Table of contents

some other input attributes

  • spellcheck: set to "false" to maximize security (otherwise spellcheck is run by a third-party service)
  • autocorrect: set to "off" in password field for instance
  • autocapitalize: set to "none" in password field for instance
  • autocomplete: precise what data can be automatically filled ("name", "new-password" etc., see list on MDN) or just set to "on" for non-sensible data and let the browser do the job
  • novalidate: if present, form-data (input) should not be validated when submitted

If type attribute is submit or image and if you want to proceed with a different action from the rest of the form with this input, use form+regularFormAttributeName to override form attributes for this specific button (ie formaction,  formenctype, formmethod, formtarget, formnovalidate

 <form action="/action_page.php">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="submit" value="Submit">
<input type="submit" formaction="/action_page2.php" formenctype="multipart/form-data" formmethod="post" formtarget="_blank" formnovalidate="formnovalidate" value="Submit as...">
</form>

Go back to Table of contents

textarea, select, datalist and output

<textarea>

Allow text edition on several lines. Use if you dare:

  • rows and cols attribues to define the size
  • maxlength and minlength attributes (based on the number of characters)
  • required attribute to avoid sending nothing
  • wrap attribute to manage going to next line when text reaches the area's edge (hard, soft, off)
  • default displayed value should be written between the opening an closing tag
<textarea name="textarea" rows="10" cols="50">Please write here.</textarea>

<select>

Use for dropdown lists. Example from W3Schools:

<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="3" multiple>
<optgroup label="Swedish Cars">
<option value="volvo" selected>Volvo</option>
  <option value="saab">Saab</option>
</optgroup>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>

selected attribute defines a pre-selected option.

size attribute defines the number of visible values

multiple attribute allow the selection of several options

Group options with optgroup element. Useful when lists are longs.

<datalist>

Specifies a list of pre-defined options for an input tag, showed depending on the user's input. Example from W3Schools:

<form action="/action_page.php">
  <input list="browsers">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
</form>

<output>

Represents the result of a calculation. Example from W3Schools:

<form action="/action_page.php" oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0 <input type="range"  id="a" name="a" value="50"> 100 +
<input type="number" id="b" name="b" value="50"> =
  <output name="x" for="a b"></output>
<br/>
<input type="submit">
</form>

Go back to Table of contents

CSS associates

For form and input tags :valid and :invalid  pseudo-classes


A look back at 2022

January 8, 2023 Reading time: 2 minutes

The end of year came so quickly I did not find the time to write a short recap. So here it is!

on a very personal perspective

  • enjoyed my new flat, city and friends
  • been anxious about a Schrödinger close friend

2023 expectations: friends & family being well; my wedding being happy

on a hobby perspective

  • read 40 books. Outsanding ones: Celle qui a tous les dons (M.R. Carey), La Force des femmes (Denis Mukwege Mukengere), Figures du communisme (Frédéric Lordon), Château l'Attente, tome 2 (Linda Medley) and L'été à Kingdom Fields (Jon McNaught)
  • failed to write a nanowrimo novel, take some time playing guitar or knit

2023 expectations: none in particular

on a volunteering work perspective

2023 expectations: publish one book

on a learning perspective

  • started refreshing my web knowledge by taking FreeCodeCamp courses
  • said byebye to Windows, welcome to Manjaro

2023 expectations: continue, finish projects, earn certifications

on a working perspective

  • reached almost 10,000km in train, most of it to reach the office 2 days a week
  • improved my xslt and audio distribution knowledge

2023 expectations: see how it goes with 1 night per month in Paris


CSS boilerplate

December 17, 2022 Reading time: 5 minutes

Here could be a CSS boilerplate for any project:

* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: 1px solid orange;
font-family: sans-serif;
}

Explanations

Selector

Using * we are targeting all elements.

Properties

margin and padding properties set to 0 are for cancelling default browser margin and padding (see this previous article). Remember:

  • use margin to determine the space around an element (values: length (fixed value), percentage (relative value to the container's width), auto (decided by the browser, usually centers horizontally))
    • top and bottom margin don't apply to replaced elements (external objects) such as iframe, video, embed, img
    • older browsers may not support flexbox, so to center an element inside its parent, also use
      margin: 0 auto;
  • use padding to determine the space inside an element (values: length or percentage)

box-sizing property is new to me. It sets how the total width and height of an element is calculated (this explanation and others as well are from MDN Web docs, completed by W3Schools): it can be either unrestricted or restricted to the parent's container.

    • default value is content-box. The calculation is:
      • element's width = witdh + padding + border
      • element's height = height + padding + border

      For instance,
      .box {
        width: 350px; 
        border: 10px solid black;
      }

      renders a box that is 350 (box width) + 10 (right border ) +10 (left border) = 370px wide.

      This means that you may have elements sharing a same width and height but if they have different paddings and/or borders, their total size will be different.

    • the other possible value for box-sizing property is border-box. This changes the calculation to:
      • element's width = witdh
      • element's height = height

      In other words, padding and border are included in the total width and height:
      .box {
        width: 350px; 
        border: 10px solid black;
      }
      renders a box that is 350px wide. This makes the world a little easier to live in, dosen't it?

border property to debug positioning drama - you should of course delete or comment (just in case haha) this line for going-live and chose a good contrasting color . I confess, when it comes to add some CSS I often feel not knowing why it's not behaving as expected. So just like many fellows, I'm adding borders to elements and yes, it helps a lot. To avoid repeating it, I put it inside the all selector (*).

font-family property to sans-serif just to make a first step out of raw HTML, it's totally subjective.


icons and emoji accessibility

December 10, 2022 Reading time: 4 minutes

I recently discovered about Font Awesome and Unicode emojis. I thought: this a great way to have images without actually hosting them! As I'd like my projects to require a minimum of ressources that may suit my needs. But wait. I'd like these projects to also be as accessible as possible. How can you achieve that when this HTML element (for font awesome) and character (for Unicode emoji) are not HTML images (<img>) and therefore cannot have an alt attribute containing the relevant alternative text?

Let's dig this out!

Font Awesome

Well, for Font Awesome, the answer is on their website, they have a dedicated section! It is beautifully sumed up on Upyouray11.com so I'll just try to sum up the sum up, so to have a reference somewhere on my own blog.

Decorative image

Hide it from assistive technologies with aria-hidden attribute, value true.

<i aria-hidden="true" class="fas fa-car"></i>

Action image

Hide the icon itself but indicate the link purpose (menu, home, cart...) with aria-label attribute on the action HTML element

<a href="/" aria-label="Home">
  <i aria-hidden="true" class="fas fa-home"></i>
</a>

Meaningful images

Hide the alternative text in a span element via CSS so it's dedicated to assistive technologies

HTML would be

<i aria-hidden="true" class="fas fa-plant" title="Vegetarian"></i>
<span class="screen-reader-only">Vegetarian</span>

Note that we are adding a title attribute to help sighted mouse users

CSS would be

.screen-reader-only {
  position: absolute;
  left: -10000px;
  top: auto;
  width: 1px;
  height: 1px;
  overflow: hidden;
}

Unicode emojis

Decorative image

Hide it from assistive technologies with aria-hidden attribute, value true in an additionnal span element:

<span aria-hidden="true">&#x1F4D6;</span>

Other images

Nest the emoji into a span element and give it a role attribute, value img and the alternative text in aria-label attribute's value:

<span role="img" aria-label="open book">&#x1F4D6;</span>

Now, let's apply this in this blog's contents!