Two steps are required when it comes to building grid designs:
Imagine we work with following code:
<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
</div>
The corresponding CodePen is of course available.
First, we need our container to display its content as a grid : #container { display: grid; }
. After that we need to slice down the container. There's two ways to do that:
#container {
display: grid;
grid-gap: 1em;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
Here we'll have a grid of 2 columns and 2 rows.
#container {
display: grid;
grid-gap: 1em;
grid-template-areas:
"div1 div2"
"div3 div4"
}
Same here but we use names. In both cases we set up a gap, which is the space between the child element of the container.
#div1 {
grid-column: 1;
grid-row: 1;
}
div1 will go in first column and first row.
#div1 {
grid-area: div1;
}
Here we declare the element's name. As div1 was the first name on the first line, #div1 element will go on first column and first row.
For the slicing part, we can use different units, exclusively or in a combination, such as:
We can also use functions, exclusively or in combination, such as:
For the filling part, we can set up precise coordinates which will be a line or a column line number with the syntax from / to
For instance, if our first div was supposed to fill the entire first line, we could write:
#div1 {
grid-column: 1 / 3;
grid-row: 1;
}
Where we are telling the brower to extend #div1 on column 1 and 2 (column 1 is between number 1 and 2 and column 2 between number 2 and 3).
Target the right element is a must-know. Here's a recap of the available options. Examples are for the following structure:
<h2>Some title</h2>
<p>A paragraph</p>
<div>
<p>I am child of div</p>
<p>The guy up there is my bro.</p>
<section>
<p>Lonely paragraph</p>
</section>
<p>Third brother.</p>
</div>
<p>Out of div</p>
<p>Same</p>
As always, a demo is available on CodePen.
Separate the elements with a ,.
h2, section {
font-weight: bolder;
color: navy;
}
Separate the parent element from the descendant element with a space.
div p {
text-decoration: underline;
}
Separate the parent element from the child element with a >.
body > p {
font-family: monospace;
}
Separate the first bro element from the second with a +.
div + p {
text-align: center;
}
Separate the first bro element from the other ones ~.
div ~ p {
width: 20%;
padding: 0.5em;
border: 0.25em solid indianred;
}
A full list can be found on MDN Web Docs.
Use a pseudo class after the element's name you want to target:
p:first-child {
letter-spacing: 0.25em;
}
p:nth-of-type(3n) {
color: blue;
}
Locate a starting point then create inline elements or specific decoration. For instance:
h2::before {
content: "♥ ";
}
h2::selection {
background-color: gold;
}
There's no attribute in the demo page. See attribute selectors
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);