I may have been stuck in xml model or several years ago but in the Uni course I learned that a HTML5 document doesn't validate if you close self-closing elements. You should write <img src="" alt="">,
<br>,
<hr>
etc. and not <br/>
and so on.
Here's the W3C HTML5 validator: https://validator.w3.org/nu/#textarea. You can also add an extension to your code editor.
Also, the closing tag may be omitted if a block element follows, for instance:
<p>Some text added
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
is valid.
Confusing, eh!
Happy New Year from New Zealand! This is a schedulded post
2023 was amazingly dense. Here's a snapshot of my walk through the year.
Thanks to FreeCodeCamp and W3Schools I made first steps with JavaScript libraries like React and jQuery and with CSS libraries like Bootstrap and Sass. React in particular was quite a challenge but in the end it was a good introduction to the component world, I feel like it will be very useful - and that is just the beginning.
Also, after proof-reading the two books that were released at les éditions du samedi in October, I went back into building EPUBs. I’m more comfortable in this exercise now I’m more familiar with command line (for executing epubcheck for instance) and since I’ve refreshed my HTML/CSS knowledge. I'm rather happy with the result!
Last but not least, I made progress in understanding and utilizing GitHub for Qwixx project and some others, like making my first pull request. I'm also discovering how Bludit is built and the existing plugins, for example I installed Disqus to allow comments!
My Raspberry Pi, transformed into a server thanks to Yunohost, crashed due to its SD card that was corrupted. I rebooted it and now try to maintain it better than I did. I’m proud I found what the issue was and study how to prevent it. It was also the occasion of finding where to configure IPV6 ports and how to access the www folder via an FTP client.
My laptop is aging and the lack of memory made it freeze when coding or surfing on Firefox so I found out I could gently reboot as well as allow some more memory with a “swap file”. I’m happy I can make my computer last a little longer. My father-in-law also helped me with the electricty supply which was flickering.
I try to be patient. I try to be kind to myself. These are not my strongest skills and I often feel like I'm wasting precious time trying to resolve a problem or understand a concept without making progress. Fortunately my wife* helps me and encourages me. Future me, please remember you have the right to find a topic challenging. Give it the time it needs and let it rest for a while if you feel you're stuck.
On the other hand, I think I'm rather good at planning. I'm happy I found a way to make progress on the Qwixx project by cutting it down to managable improvments (adding controls on user input), one step at a time. I also find it useful to blog on what I learn, at the moment (searching, explaining with my words) and later on (I'm often looking for previous posts for Boilerplates or Flexbox for instance!).
Aaand there's work as well. 4 days a week, not nothing! I was not far away from a burn out at the beginning of the year but it was better and brighter on the end. There is some projects to come I'm very excited about and I feel I'm more efficient with my programming skills (on XSLTs) and with understanding how things go together.
Well, it's been a year that a close friend is imprisoned. He’s keeping up. I would very much like to hug him again. Also on the dark side, my wife lost a childhood friend and my best friend lost her father-in-law. I did my best to give them support. Show love when you can!
*Yes, on the bright side the big news is that I got married! It was a lot of stress, of money and prep but well, love shines above all haha It was a beautiful and rainy and awesome day but wah, this is exhausting and neverending (thank you cards to send!)
In 2024 I'll take a University course on my free time. So I think I'll continue learning web development!
What I'd like to achieve on computer science side:
Learning React on FreeCodeCamp was confusing. For the first time in the curriculum I had to find some tutorials and go through W3C course as well to help me out. Let's hope writing down will help me understand how to use it.
A JavaScript library to build user interfaces thanks to its own markup language called JSX (combination of HTML and JavaScript). It was created and is maintained by Facebook.
React splits up the web page structure to separate components that can be displayed (rendered) according to a set of rules. To execute the rendition, the browser will need a transpiler (a converter) such as Babel.
React uses a virtual DOM where it does all the changes before passing them to the browser DOM.
Pen Settings/JS tab: select Babel as JavaScript Preprocessor
On JS tab add
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@18.2.0";
import * as React from "https://cdn.skypack.dev/react@18.2.0";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
)
And on HTML tab add
<div id="root"></div>
Make sure npx and Node.js are installed, then open a terminal and
ncd Documents/...
)npx create-react-app my-react-app
(my-react-app is the name of your app/directory)Wait a few minutes and it the React environment be ready. Then (and anytime later when located on your project directory), just run npm start
. A new browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000
in the address bar. Changes you make will be visible immediately after you save the file, without reloading.
See all basics examples on CodePen. Each part is rendered in a different section for a better understanding but in this article we keep the rendering in a div with an id of root which is more common in real life.
React components are named functions that return HTML. If you have a project on your hardrive, you can split your work: 1 component equals 1 js file (Capitalized).
For instance:
in App.css
.red {color: red}
in Hello.js
function Hello() {
return <h2>Hello World!</h2>
}
export default Hello;
in App.js
import Hello from './Hello'
import './App.css';
function App() {
return <>
<h1 className="red">This is the App Name</h1>
<Hello/>
</>
}
Will be translated as:
<div id="root">
<h1 class="red">This is the App Name</h1>
<h2>Hello World!</h2>
</div>
Observations:
<>
and </>
fragment to enclose your code if there's no HTML tag to encapsulate it.Components can recieve properties (which would act as function arguments) from element's attributes. For instance:
function Yummy(prop) {
return <p>I love {prop.treat}!</p>
}
ReactDOM.render(
<React.StrictMode>
<Yummy treat="cookies" />
</React.StrictMode>,
document.getElementById("root")
)
prop
will regroup all attributes and children that where provided in an object, this is why we use the dot notation un Yummy fonction. If there's only a few attributes, we can just import in the function the needed key:
function Yummy( {treat, children} ) {
return <p>I love {treat}! {children ? <strong>{children}</strong> : "Reasonably."}</p>
}
ReactDOM.render(
<React.StrictMode>
<Yummy treat="chocolate">
<em>Too much, actually.</em>
</Yummy>
</React.StrictMode>,
document.getElementById("root")
)
Note that the code to be treated as JavaScript should be within curly braces. Methods (functions) can be passed as properties.
Let's have a look at this example for W3schools:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(
<React.StrictMode>
<Football />
</React.StrictMode>,
document.getElementById("root")
)
Observations:
onClick
instead of onclick
)In this example, also from W3schools, we use two methods: && operator and ternary operator. We could also have used a classic if/else statement based on a prop value for instance (if prop is true, show this, else, show that).
function Garage(props) {
const cars = props.cars;
const message = `You have ${cars.length} cars in your garage.`;
return (
<>
<h3>Garage</h3>
{cars.length > 0 &&
<p>
Using && :<br/>
{message}
</p>
}
{
cars.length > 0 ?
<p>Using ternary operator :<br/>{message}</p> :
null
}
</>
);
}
const listofcars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
]
ReactDOM.render(
<React.StrictMode>
<Garage cars={listofcars} />
</React.StrictMode>,
document.getElementById("root")
)
Note: to use a variable within a string, nest the string intro backticks (`) and let you variable into curly brackets be preceded by a $ sign.
Use key for re-rendering only the element of a list that has been updated. Using the same listofcars
constant from above as well as the map JavaScript method (which iterates every item of provided list):
function Car(props) {
return <li>{ props.brand }</li>;
}
function Vroum() {
return (
<>
<h1>List of cars</h1>
<ul>
{listofcars.map((listofcars) => <Car key={listofcars.id} brand={listofcars.brand} />)}
</ul>
</>
);
}
ReactDOM.render(
<React.StrictMode>
<Vroum />
</React.StrictMode>,
document.getElementById("root")
)
Hooks connects rendering to particular changes which will be described here after. They replace class components since version 16.8. They can be customed, otherwise some are pre-made. All examples comes from W3Schools and are available on this CodePen.
First of all, if you have not imported all React features (using import * as React from
...), import the hooks you need, for instance:
import { useState, useEffect } from "react";
Doing so you are destructuring useState
from react
and can use it as is (rather than specify React.useState
like in CodePen).
And keep in mind these 3 rules from W3Schools:
- Hooks can only be called inside React function components.
- Hooks can only be called at the top level of a component.
- Hooks cannot be conditional
In this article we'll just focus on three main hooks but feel free to explore the other existing ones (useContext, useReducer, useCallback, useMemo).
Links a variable (its current state) to an updater function.
function App() {
const [color, setColor] = useState("yellow");
return <>
<p>My favorite color is {color}!</p>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
</>
}
Observations:
setVariablename
)useState("yellow")
initiates the variable to the value "yellow"
(a string)"blue"
as an argument (setting up a new state for color
)function App() {
const [car, setCar] = useState({
brand: "Ford",
model: "Mustang",
year: "1964",
color: "red"
});
const updateColor = () => {
setCar(previousState => {
return { ...previousState, color: "blue" }
});
}
return (
<>
<h1>My {car.brand}</h1>
<p>
It is a {car.color} {car.model} from {car.year}.
</p>
<button
type="button"
onClick={updateColor}
>Blue</button>
</>
)
}
Observations:
...previousState
) and indicate the change afterwards. Otherwise the entire object will be replaced with the only pair color: "blue"
.Perform side effect like fetching data, updating DOM, play with timers and runs on every render. Don't forget the second parameter (an empty array or an array containing dependencies) which will prevent auto re-rendering.
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // if count updates, update calculation variable
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
If there's a useEffect
hook on a timer, it should be disposed to reduce memory leaks; for this name the te timer and use a return statement to clear it:
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
return () => clearTimeout(timer)
}, []);
return <h1>I've rendered {count} times!</h1>;
}
Can be used to access a DOM element directly or to keep track of previous state value. useRef()
returns an object called current
which should be intialized.
function Pointer() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
Using useRef, we associate the inputElement variable and the HTML element which have a ref attribute containing the variable's name. This is useful when we can't use getElementBySomething
because the real DOM is not already built.
function Before() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}
Both inputValue and previousInputValue are initialized to an empty string. Each time there's an event (e) in the input field:
inputValue
is updated via the setInputValue useState
function and the variable equals field's content
inputValue
is changed and as it's a depedancy, useEffect
comes in and replaces the value of current property to be equal to the inputValue
. It is not re-rendered until there's another event in the input field.We're done for now! Happy coding
A very popular JavaScript library which offers a lot of methods for common tasks. It includes useful features such as:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
$(document).ready(function(){Using jQuery within the document calling it is also fine, it's just a suggestion for clarity.
// jQuery methods go here...
});
Basic syntax is: $(selector).action();
The selector is mainly CSS (for instance "#id"
) but can also be the keyword this
to find the current element.
Event syntax is: $(selector).eventname();
Use vanilla JavaScript event names. A noticable special event would be hover()
(combination of mouseenter()
and mouseleave()
)
Run multiple jQuery methods by chaining them:
$(selector) .action1() .action2 .action3
(indentation and line breaks are fine)
$(selector).hide(speed,callback);
(same goes with .show()
and .toggle()
, parameters are optional)
$(selector).text(); // the text content of selected element
$(selector).html(); // the HTML content of selected element
$(selector).val(); // the value of form fields
$(selector).attribute("attributename"); // the attribue value
Without parameters, you'll get. For setting, pass a parameter
$("#test1").text("Hello world!"); $("#test1").attribute("href", "https://another.website");
Note that .text
, .html
and .val
methos come with a callback function having 3 parameters: the index of the current element in the list of elements selected and the original value. For instance:
$("#test").html(function(i, origText){
return "Old html: " + origText + " New html: Hello <b>world!</b>
(index: " + i + ")";
});
To add content at the end of the selected element, use .append("new content")
and use .prepend("new content")
to add at the begining of the select element.
You can also target the position right after the targeted element with .after()
and before with... .before()
.
The methods acceps several parameters.
Remove the selected element with .remove()
or remove all childs within the selected element with .empty()
.
You can also filter down what should be removed by passing one or more CSS selectors, separated with comas, as a parameter $("p").remove(".test, .demo");
.
$(selector).addClass(); // add class (could be several)
$(selector).removeClass(); // remove class (could be several)
$(selector).toggleClass(); // adds or remove class given
$(selector).css("propertyname"); // the property value
Separator between classes is a blank space $("#div1").addClass("important blue");
In .css
method, if you want to pass property + value, use this syntax:
$("p").css("background-color", "yellow");
$("p").css({"background-color": "yellow", "font-size": "200%"});
Basic syntax $(selector).relation();
It is possible to add an optional parameter (a CSS selector) to filter the search.
$(selector).parent() // returns direct parent element
$(selector).parents() // returns all ancestor elements up to document's root
$(selector).parentsUntil("div") // returns all ancestor elements in between
$(selector).children() // returns all direct children
$(selector).find() // returns all descendant elements down to last descendant
siblings() // all sibling elements
next() // next sibling element
nextAll() // all next siblings elements
nextUntil() // all siblings in between
prev()
// previous sibling element
prevAll()
// all previous siblings elements
prevUntil()
// all siblings in between (backwards)
Most basic filtering methods are first()
, last()
and eq()
to select a specific element based on its position.
And also of course filter()
: elements that don't match are removed from the selection and not():
the opposite.
Load data from a server and return it in the selected element: $(selector).load(URL,data,callback);
Optional callback function can have these three parameters:
responseTxt
- resulting content if the call succeedsstatusTxt
- status of the callxhr
- XMLHttpRequest objectExample from W3schools.com:
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
You can also exchange data with a sever using an HTTP request (GET or POST).
$.get(URL,callback);
$.post(URL,data,callback);
I'm taking w3schools HTML course as a refresher and I learned a few things along the way.
I knew about blockquote but not sure about the other two.
Quote from another source:
Short inline quote:
Indicate the title of a work:
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
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.
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>
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:
As well as a start attribute to chose from which number to start.
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>
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>
From W3Schools.
Landmarks define some parts of the page to jump to with the help of a screen reader #accessibility
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 stands for keyboard inuput. Default browser's display is monospace font.
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".
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>.
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.
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>
Some code snippets are available on my dedicated CodePen
Encapsulate your section into a container class which can be either:
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:
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>
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.
Classes for colors are:
element could be text, bg, alert, btn
Some useful class for img element:
To create a gallery, combine thumbnail class with Bootstrap grid system:
figure
that will contain a link to the image source full size that will itself containelement
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">×</a>
<strong>Success!</strong> Indicates a successful or positive action.
</div>
button
, a
, input
Basic classes to apply on a button
, a
or input
elements are:
Then add if needed:
a
& button
groupsA 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.