<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Salvietta150x40</title>
    <description>The latest articles on DEV Community by Salvietta150x40 (@salvietta150x40).</description>
    <link>https://dev.to/salvietta150x40</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F139424%2F38e19eda-87ec-4d77-a96c-a57c663895b6.jpg</url>
      <title>DEV Community: Salvietta150x40</title>
      <link>https://dev.to/salvietta150x40</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/salvietta150x40"/>
    <language>en</language>
    <item>
      <title>How to upload files to the server using JavaScript</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Wed, 14 Jun 2023 11:23:39 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/how-to-upload-files-to-the-server-using-javascript-4lo5</link>
      <guid>https://dev.to/salvietta150x40/how-to-upload-files-to-the-server-using-javascript-4lo5</guid>
      <description>&lt;p&gt;In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to upload an avatar, a thumbnail, a PDF file or any other image or file in various formats.&lt;/p&gt;

&lt;p&gt;We are going to structure this tutorial in several parts. First we will create the project, then we will create the frontend code and finally the backend code for the server.&lt;/p&gt;

&lt;p&gt;To understand this tutorial you will need some basic knowledge of the command line. If you have never used the command line before, see the following command line tutorial, which explains some basic commands for the most commonly used operating systems. You will also need to have both Node.js and the npm package manager installed. &lt;/p&gt;



&lt;h3&gt;
  
  
  Creating the project
&lt;/h3&gt;

&lt;p&gt;The first thing we are going to do is to configure and create the project. To do this, create an empty directory somewhere, access it via the command line and use the following command to create the project:&lt;/p&gt;


&lt;pre&gt;npm init&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;We only need to install two packages. First install express using the following command:&lt;/p&gt;


&lt;pre&gt;npm install express&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;Next we will also need a middleware for express called express-fileupload which we can use to manage the files that are sent to the server:&lt;/p&gt;


&lt;pre&gt;npm install express-fileupload&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;Next, configure the file that will create the express server. To do this, edit the package.json file, which should contain the line "start": "node index.js" in the scripts section to tell Node which file to run when we start the application:&lt;/p&gt;


&lt;pre&gt;{&lt;br&gt;&lt;br&gt;
"name": "ulpload-file-ajax",&lt;br&gt;&lt;br&gt;
"description": "Tutorial in which an ajax medium file is created",&lt;br&gt;&lt;br&gt;
"version": "1.0.0",&lt;br&gt;&lt;br&gt;
"dependencies": {&lt;br&gt;&lt;br&gt;
  "express": "4.16.2",&lt;br&gt;&lt;br&gt;
  "express-fileupload": "^1.1.7-alpha.3",&lt;br&gt;&lt;br&gt;
  "request": "^2.88.2"&lt;br&gt;&lt;br&gt;
},&lt;br&gt;&lt;br&gt;
"scripts": {&lt;br&gt;&lt;br&gt;
  "start": "node index.js"&lt;br&gt;&lt;br&gt;
 }&lt;br&gt;&lt;br&gt;
}&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;Next, we create the index.js file in the root folder of the project and we add the necessary code for the creation of a basic server:&lt;/p&gt;


&lt;pre&gt;&lt;br&gt;
const express = require('express');&lt;br&gt;
const router = express.Router();

&lt;p&gt;const bodyParser = require('body-parser');&lt;br&gt;
const fileupload = require('express-fileupload');&lt;br&gt;
const FileController = require('./controllers/FileController');&lt;/p&gt;

&lt;p&gt;const app = express();&lt;br&gt;
const fileController = new FileController();&lt;/p&gt;

&lt;p&gt;app.use(bodyParser.json());&lt;br&gt;
app.use(bodyParser.urlencoded({ extended: true }));&lt;br&gt;
app.use(fileupload());&lt;/p&gt;

&lt;p&gt;router.post('/ulpload-file', fileController.uploadFile);&lt;/p&gt;

&lt;p&gt;router.use(function(req, res) {&lt;br&gt;
   res.status(404).json({&lt;br&gt;
     error: true,&lt;br&gt;
     message: 'Not Found'&lt;br&gt;
   });&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;app.use('/api', router);&lt;/p&gt;

&lt;p&gt;app.use(express.static(__dirname));&lt;br&gt;
app.get('/', function (req, res) {&lt;br&gt;
   res.render('index.html');&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;var port = 3000;&lt;br&gt;
app.listen(port, function () {&lt;br&gt;
   console.log('Server', process.pid, 'listening on port', port);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;module.exports = app;&lt;br&gt;
&lt;/p&gt;&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;What we have done is to create the server. At the top of the file we have made a require of the &lt;code&gt;express-fileupload&lt;/code&gt; module, which is essential for uploading files.&lt;/p&gt;

&lt;p&gt;We have included the &lt;code&gt;FileController&lt;/code&gt; class, located in the &lt;code&gt;/controllers/FileController.js&lt;/code&gt; file, although we haven't created it yet. In the &lt;code&gt;uploadFile&lt;/code&gt; function of this controller is where we will add the code in charge of uploading the file.&lt;/p&gt;

&lt;p&gt;As for the path that will redirect the request to the controller, we have defined the path &lt;code&gt;/api/upload-file&lt;/code&gt; using the following function:&lt;/p&gt;


&lt;pre&gt;router.post('/upload-file', fileController.uploadFile);&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;We have added the &lt;code&gt;/api&lt;/code&gt; prefix to the path using the following statement:&lt;/p&gt;


&lt;pre&gt;app.use('/api', router);&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;Please have a look at this file, as we will be creating the frontend code next.&lt;/p&gt;



&lt;h3&gt;
  
  
  2. Frontend JavaScript code&lt;/h3&gt;
&lt;br&gt;


&lt;p&gt;In this section we will add the frontend code in charge of sending the file from the user's system to the server. To start, create the &lt;code&gt;index.html&lt;/code&gt; file in the root folder of the project. Next, edit the file you just created and copy and paste the following code, which we will explain later:&lt;/p&gt;


&lt;pre&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;&lt;br&gt;
&amp;lt;html lang="es"&amp;gt;&lt;br&gt;&lt;br&gt;
 &amp;lt;head&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;meta charset="utf-8" /&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;meta http-equiv="x-ua-compatible" content="ie=edge" /&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1" /&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;title&amp;gt;Ajax Node File Upload Tutorial&amp;lt;/title&amp;gt;&lt;br&gt;&lt;br&gt;
 &amp;lt;/head&amp;gt;&lt;br&gt;&lt;br&gt;
 &amp;lt;body&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;h1&amp;gt;Ajax Node File Upload Tutorial&amp;lt;/h1&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;p&amp;gt;&amp;lt;label&amp;gt;Select a new file!&amp;lt;/label&amp;gt;&amp;lt;/p&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;input type="file" id="upload_file" /&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;div id="result"&amp;gt;&amp;lt;/div&amp;gt;&lt;br&gt;&lt;br&gt;
   &amp;lt;script type="text/javascript" src="resources/js/scripts.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;br&gt;&lt;br&gt;
 &amp;lt;/body&amp;gt;&lt;br&gt;&lt;br&gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;What we have done is to add a basic HTML5 template. We have also added an HTML &lt;code&gt;input&lt;/code&gt; field, which is the field that the user will interact with to upload the file:&lt;/p&gt;



&lt;pre&gt;&amp;lt;input type="file" id="upload_file" /&amp;gt;&lt;/pre&gt;



&lt;p&gt;As you can see, we've linked to the &lt;code&gt;/resources/js/scripts.js &lt;/code&gt; script just before the closing &lt;code&gt;&amp;lt;/body&amp;gt;&lt;/code&gt; tag. Let's add it, so first create the &lt;code&gt;/resources/js&lt;/code&gt; directory and then create and edit the &lt;code&gt;scripts.js&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Now we are going to add the JavaScript code that will allow us to associate an event to the field we have created in order to upload the file to the server. First we will see the code and then we will explain it:&lt;/p&gt;


&lt;pre&gt;&lt;br&gt;
const uploadImage= event =&amp;gt; {&lt;br&gt;
 const files = event.target.files;&lt;br&gt;
 const data = new FormData();&lt;br&gt;
 data.append('file', files[0]);&lt;br&gt;
 fetch('/api/upload-file', {&lt;br&gt;
    method: 'POST',&lt;br&gt;
    body: data&lt;br&gt;
 })&lt;br&gt;
 .then(response =&amp;gt; response.json())&lt;br&gt;
 .then(data =&amp;gt; {&lt;br&gt;
   document.getElementById('result').innerHTML = 'The file ' + data.path + ' has been successfully uploaded.';&lt;br&gt;
 })&lt;br&gt;
 .catch(error =&amp;gt; {&lt;br&gt;
    console.error(error);&lt;br&gt;
 });&lt;br&gt;
}&lt;br&gt;
document.querySelector('#upload_file').addEventListener('change', event =&amp;gt; {&lt;br&gt;
   uploadImage(event);&lt;br&gt;
});&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;
In the last block of code we have registered a &lt;code&gt;change&lt;/code&gt; event for the input we use to upload the file. In this event we execute the function &lt;code&gt;uploadImage&lt;/code&gt;, which receives as parameter the click event itself, from where we will have access to the selected file.&lt;/p&gt;

&lt;p&gt;What we do in the &lt;code&gt;uploadImage&lt;/code&gt; function is to get the selected file, located in the &lt;code&gt;event.target.files&lt;/code&gt; array. Then we create a &lt;code&gt;FormData&lt;/code&gt; object and assign the selected file to it. Finally we use the fetch function to send a &lt;code&gt;POST&lt;/code&gt; request to the &lt;code&gt;/api/upload-file&lt;/code&gt; path we created on the server. &lt;/p&gt;

&lt;p&gt;Then we check if the file upload has been completed successfully, printing in the &lt;code&gt;result&lt;/code&gt; field the file path if it has been uploaded correctly, or displaying an error in the console otherwise. We return the path in the &lt;code&gt;path&lt;/code&gt; property.&lt;/p&gt;
&lt;h3&gt;
  
  
  3. Node.js Backend Code&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Now let's take a look at the process that is followed on the server to upload the file. The first thing you need to do is create the &lt;code&gt;/uploads&lt;/code&gt; directory in the root folder of your project. This is the directory where we will upload the files.&lt;/p&gt;

&lt;p&gt;We're going to create the &lt;code&gt;/controllers/FileController.js&lt;/code&gt; file as a controller. As before, we'll first look at the code for this file and then explain how it works:&lt;/p&gt;


&lt;pre&gt;class FileController&lt;br&gt;
{&lt;br&gt;
  uploadFile = async (req, res, next) =&amp;gt;&lt;br&gt;
  {&lt;br&gt;
   const file = req.files.file;&lt;br&gt;
   const fileName = file.name;&lt;br&gt;
   const path = __dirname + '/../uploads/' + fileName;

&lt;p&gt;try {&lt;br&gt;
    file.mv(path, (error) =&amp;gt; {&lt;br&gt;
     if (error) {&lt;br&gt;
     console.error(error);&lt;br&gt;
     res.writeHead(500, {&lt;br&gt;
       'Content-Type': 'application/json'&lt;br&gt;
  });&lt;br&gt;
   res.end(JSON.stringify({ status: 'error', message: error }));&lt;br&gt;
     return;&lt;br&gt;
   }&lt;br&gt;
   return res.status(200).send({ status: 'success', path:'/uploads/' + fileName });&lt;br&gt;
  });&lt;br&gt;
  } catch (e) {&lt;br&gt;
   res.status(500).json({&lt;br&gt;
    error: true,&lt;br&gt;
    message: e.toString()&lt;br&gt;
   });&lt;br&gt;
  }&lt;br&gt;
 }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;module.exports = FileController;&lt;br&gt;
&lt;/p&gt;&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;We have created a class called &lt;code&gt;FileController&lt;/code&gt; as a controller, in which we have defined the &lt;code&gt;uploadFile&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;The first thing we do is to get the file we have sent, which should be in the variable &lt;code&gt;req.files.file&lt;/code&gt;, since &lt;code&gt;file&lt;/code&gt; was the name we have given it in the frontend code. Now we can get the name of the file, which will be in the variable &lt;code&gt;file.name&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next, we have defined the &lt;code&gt;path&lt;/code&gt; where we are going to copy the file and then, using the function &lt;code&gt;file.mv&lt;/code&gt;, we copy the file to that path.&lt;/p&gt;

&lt;p&gt;In case the file has been copied successfully, we will send the response back in JSON format:&lt;/p&gt;


&lt;pre&gt;return res.status(200).send({ status: 'success', path:'/uploads/' + fileName });&lt;/pre&gt;
&lt;br&gt;

&lt;p&gt;Otherwise, an error is returned.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Testing the app&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Let's test the application to verify that everything works correctly. To do this, open a terminal window and go to the root folder of the project. Then run the following command to start the server:&lt;/p&gt;


&lt;pre&gt;npm start&lt;/pre&gt;
&lt;br&gt;&lt;br&gt;
Then go to the URL &lt;code&gt;&lt;a href="http://localhost:3000/"&gt;http://localhost:3000/&lt;/a&gt;&lt;/code&gt; and try uploading a file, such as an image in &lt;code&gt;.png&lt;/code&gt; or &lt;code&gt;.jpg&lt;/code&gt; format.

&lt;p&gt;And that is all.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>json</category>
    </item>
    <item>
      <title>How to Track Flight Status in real-time using the Flight Tracker API</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Tue, 06 Jun 2023 09:21:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/how-to-track-flight-status-in-real-time-using-the-flight-tracker-api-3lbn</link>
      <guid>https://dev.to/salvietta150x40/how-to-track-flight-status-in-real-time-using-the-flight-tracker-api-3lbn</guid>
      <description>&lt;p&gt;The Flight Tracker API provides developers with the ability to access real-time flight status, which is extremely useful for integrating historical tracking or live queries of air traffic into your website.
&lt;/p&gt;

&lt;p&gt;With this API, you can easily track the status of a flight and access airport schedules.
&lt;/p&gt;

&lt;p&gt;There are several Flight Tracker APIs available to retrieve flight status, and one of the best options is aviationstack. This API offers a simple way to access aviation data globally, including real-time flight status and airport schedules.
&lt;/p&gt;

&lt;p&gt;Aviationstack tracks every flight worldwide at all times, storing the information in its database and providing real-time flight status through its API. It is a user-friendly REST API that returns responses in JSON format and is compatible with various programming languages such as PHP, Python, Ruby, Node.js, jQuery, Go, and more.
&lt;/p&gt;

&lt;p&gt;In this tutorial, we will show you how to obtain real-time flight status using the aviationstack Flight Tracker API with PHP.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;Obtaining API Credentials
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;To get started, you need to create an account on aviationstack. Once you are in your dashboard, you can copy the API access key from the "&lt;strong&gt;Your API Access Key&lt;/strong&gt;" section.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;API Configuration
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;We will need the access key to authenticate and access the &lt;a href="aviationstack.com/product" rel="nofollow noreferrer noopener"&gt;aviationstack&lt;/a&gt; API.
&lt;/p&gt;

&lt;p&gt;Next, we will build the query using the 
  &lt;code&gt;http_build_query() 
  &lt;/code&gt; function to pass the necessary parameters to the aviationstack API.
&lt;/p&gt;

&lt;p&gt;Define the access key in the 
  &lt;code&gt;access_key 
  &lt;/code&gt; parameter.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
$queryString = http_build_query([
'access_key' =&amp;gt; 'YOUR_ACCESS_KEY'
]);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;HTTP GET Request
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;To retrieve flight data, we will make an 
  &lt;code&gt;HTTP GET 
  &lt;/code&gt; request to the aviationstack API using cURL.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
// API URL with the query string
$apiURL = sprintf('%s?%s', 'https://api.aviationstack.com/v1/flights', $queryString);
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the API request
$api_response = curl_exec($ch);
// Close cURL
curl_close($ch);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;It is important to ensure that the API call is secure, so we should use the URL with 
  &lt;code&gt;https 
  &lt;/code&gt;:
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://api.aviationstack.com" rel="nofollow noreferrer noopener"&gt;https://api.aviationstack.com&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;Flight Status and General Information
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;After making the API call, we will receive the current flight status and related information in JSON format. Initially, the aviationstack API provides the following geolocation data:
&lt;/p&gt;

&lt;p&gt;- Flight date (flight_date)
  &lt;br&gt;
  - Flight status (flight_status)
  &lt;br&gt;
  - Departure and arrival information (departure/arrival)
  &lt;br&gt;
  - airport
  &lt;br&gt;
  - timezone
  &lt;br&gt;
  - iata
  &lt;br&gt;
  - icao
  &lt;br&gt;
  - terminal
  &lt;br&gt;
  - gate
  &lt;br&gt;
  - delay
  &lt;br&gt;
  - scheduled
  &lt;br&gt;
  - estimated
  &lt;br&gt;
  - actual
  &lt;br&gt;
  - estimated_runway
  &lt;br&gt;
  - actual_runway
&lt;/p&gt;

&lt;p&gt;- Airline information (airline)
  &lt;br&gt;
  - name
  &lt;br&gt;
  - iata
  &lt;br&gt;
  - icao
&lt;/p&gt;

&lt;p&gt;- Flight information (flight)
  &lt;br&gt;
  - number
  &lt;br&gt;
  - iata
  &lt;br&gt;
  - icao
  &lt;br&gt;
  - codeshared
&lt;/p&gt;

&lt;p&gt;- Aircraft information (aircraft)
  &lt;br&gt;
  - registration
  &lt;br&gt;
  - iata
  &lt;br&gt;
  - icao
  &lt;br&gt;
  - icao24
&lt;/p&gt;

&lt;p&gt;- Live data (live)
  &lt;br&gt;
  - updated
  &lt;br&gt;
  - latitude
  &lt;br&gt;
  - longitude
  &lt;br&gt;
  - altitude
  &lt;br&gt;
  - direction
  &lt;br&gt;
  - speed_horizontal
  &lt;br&gt;
  - speed_vertical
  &lt;br&gt;
  - is_ground
&lt;/p&gt;

&lt;p&gt;By using the 
  &lt;code&gt;json_decode()  
  &lt;/code&gt;function, we can convert the obtained JSON data into a PHP array.
&lt;/p&gt;

&lt;p&gt;Here's an example of how to extract flight information using the aviationstack API:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
$api_result = json_decode($api_response, true);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Below is the complete code to retrieve global flight information using the aviationstack API with PHP:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;&lt;br&gt;// Define the API access key&lt;br&gt;$queryString = http_build_query([&lt;br&gt;    'access_key' =&amp;gt; 'YOUR_ACCESS_KEY',&lt;br&gt;    'limit' =&amp;gt; 10&lt;br&gt;        ]);&lt;br&gt;// API URL with the query string&lt;br&gt;$apiURL = sprintf('%s?%s', 'https://api.aviationstack.com/v1/flights', $queryString);&lt;br&gt;// Initialize cURL&lt;br&gt;$ch = curl_init();&lt;br&gt;curl_setopt($ch, CURLOPT_URL, $apiURL);&lt;br&gt;curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);&lt;br&gt;// Execute the API request&lt;br&gt;$api_response = curl_exec($ch);&lt;br&gt;// Close cURL&lt;br&gt;curl_close($ch);&lt;br&gt;// Convert the JSON into an array&lt;br&gt;$api_result = json_decode($api_response, true);&lt;br&gt;// Display flight data&lt;br&gt;foreach ($api_result['data'] as $flight) {&lt;br&gt;  if (!$flight['live']['is_ground']) {&lt;br&gt;    echo sprintf("%s flight %s from %s (%s) to %s (%s) is in the air.",&lt;br&gt;            $flight['airline']['name'],&lt;br&gt;            $flight['flight']['iata'],&lt;br&gt;            $flight['departure']['airport'],&lt;br&gt;            $flight['departure']['iata'],&lt;br&gt;            $flight['arrival']['airport'],&lt;br&gt;            $flight['arrival']['iata']&lt;br&gt;    ), PHP_EOL;&lt;br&gt;    echo '&amp;lt;br/&amp;gt;';&lt;br&gt;  }&lt;br&gt;}&lt;br&gt;?&amp;gt;&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;This code allows you to retrieve updated flight information using the aviationstack API. Make sure to replace ' 
  &lt;code&gt;YOUR_ACCESS_KEY 
  &lt;/code&gt;' with your provided personal access key from aviationstack.
&lt;/p&gt;

&lt;p&gt;You can integrate this code into your PHP application to display real-time flight status and related details on your website.
&lt;/p&gt;

&lt;p&gt;Note: It's important to handle error cases, such as when the API response is not successful or when there are no flight data available. You can add error handling and additional logic as per your application requirements.
&lt;/p&gt;

</description>
      <category>php</category>
      <category>api</category>
      <category>json</category>
      <category>development</category>
    </item>
    <item>
      <title>Mastering array sorting in JavaScript: a guide to the sort() function</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Mon, 05 Jun 2023 15:54:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/mastering-array-sorting-in-javascript-a-guide-to-the-sort-function-3j7</link>
      <guid>https://dev.to/salvietta150x40/mastering-array-sorting-in-javascript-a-guide-to-the-sort-function-3j7</guid>
      <description>&lt;p&gt;In this article, I will explain the usage and potential of the 
  &lt;code&gt;sort()
  &lt;/code&gt; function in JavaScript.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does the 
  &lt;code&gt;sort()
  &lt;/code&gt; function do?&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;sort()
  &lt;/code&gt; function allows you to sort the elements of an array object. It can sort the elements in either the default ascending order or according to a custom sorting function.
&lt;/p&gt;

&lt;p&gt;By default, the function sorts the elements in ascending order based on their string Unicode values. It converts the elements to strings and then arranges them using Unicode values.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Unicode?&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Unicode is a standard that assigns a unique numeric value, known as a code point, to every character used in writing systems worldwide. It enables computers to handle and represent various languages, symbols, and tastes consistently.
&lt;/p&gt;

&lt;p&gt;For example, in the English Latin alphabet:
&lt;/p&gt;

&lt;p&gt;- U+0041 to U+005A represents the Latin capital letters (A-Z).
  &lt;br&gt;
  - U+0061 to U+007A represents the Latin small letters (a-z).
&lt;/p&gt;

&lt;p&gt;So, for instance, the word "Apple" in the Latin alphabet (English) is represented in Unicode as:
&lt;/p&gt;

&lt;p&gt;A: U+0041
&lt;/p&gt;

&lt;p&gt;p: U+0070
&lt;/p&gt;

&lt;p&gt;p: U+0070
&lt;/p&gt;

&lt;p&gt;l: U+006C
&lt;/p&gt;

&lt;p&gt;e: U+0065
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;How does 
  &lt;code&gt;sort()
  &lt;/code&gt; utilize Unicode tastes?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;
  &lt;br&gt;
  The 
  &lt;code&gt;sort()
  &lt;/code&gt; function employs a sorting algorithm to sort the array. It can use various sorting algorithms such as bubble sort, quicksort, heapsort, or mergesort, depending on factors like array size, data types, and optimization strategies implemented by the JavaScript engine.
&lt;/p&gt;

&lt;p&gt;The JavaScript engine executes the code and is responsible for interpreting and running JavaScript programs. It can be part of web browsers, server-side JavaScript platforms, or standalone JavaScript runtime environments.
&lt;/p&gt;

&lt;p&gt;Among the sorting algorithms mentioned, quicksort or its variations are commonly used for sorting arrays in JavaScript.
&lt;/p&gt;

&lt;p&gt;If you're interested in learning more about the quicksort algorithm, you can check out resources like the W3Resource website.
&lt;/p&gt;

&lt;p&gt;How to use the 
  &lt;code&gt;sort()
  &lt;/code&gt; function in JavaScript
  &lt;br&gt;
  Now that we understand how 
  &lt;code&gt;sort()
  &lt;/code&gt; works internally, let's see how to use it.
&lt;/p&gt;

&lt;p&gt;To use the function, simply call 
  &lt;code&gt;{array}.sort()
  &lt;/code&gt;. This will sort the elements in the default ascending order, as described earlier.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
javascript
const tastes = [
"Margherita",
"Napoletana",
"Quattro Formaggi",
"Primavera",
"Marinara",
"Boscaiola",
"Bufala",
];
const sortedArray = tastes.sort();
// Output:
["Boscaiola", "Bufala", "Primavera", "Margherita", "Marinara", "Quattro Formaggi", "Napoletana"];
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;As you can see in the example, the names of the tastes have been sorted in ascending order based on their Unicode representation.
&lt;/p&gt;

&lt;p&gt;If you want to have them sorted in descending alphabetical order, you can chain the 
  &lt;code&gt;reverse()
  &lt;/code&gt; function after 
  &lt;code&gt;sort()
  &lt;/code&gt;. This will reverse the order of the elements once they have been sorted.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;What about sorting numbers?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;Let's explore it:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const numbers = [9, 3, 12, 11, 40, 28, 5];
const sortedNumbers = numbers.sort();
console.log(sortedNumbers);
// Output:
[11, 12, 28, 3, 40, 5, 9];
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Mmmmmmh ,the result is not sorted in the expected order. Why?
&lt;/p&gt;

&lt;p&gt;Well, remember when I mentioned that the default sorting method uses Unicode character sorting after converting the elements to strings? That's the reason. The numbers are converted to their string equivalents and then sorted based on Unicode values.
&lt;/p&gt;

&lt;p&gt;As a consequence, all the numbers starting with '1' come before any other numbers. Therefore, '11' is sorted before '3', and so on.
&lt;/p&gt;

&lt;p&gt;Let's examine the Unicode values for these numbers:
&lt;/p&gt;

&lt;p&gt;- 11: U+0031 U+0031
  &lt;br&gt;
  - 12: U+0031 U+0032
  &lt;br&gt;
  - 28: U+0032 U+0038
  &lt;br&gt;
  - 3: U+0033
  &lt;br&gt;
  - 40: U+3034 U+0030
  &lt;br&gt;
  - 5: U+3035
  &lt;br&gt;
  - 9: U+3039
&lt;/p&gt;

&lt;p&gt;As you can see, if we sort based on Unicode tastes, the comparison between '1' and '3' results in '0031' being less than '0033'. Consequently, the numbers starting with '1' will be pushed to the front of the array.
&lt;/p&gt;

&lt;p&gt;You might find this behavior annoying. But don't worry, there's a solution: using custom compare functions.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;How to Use a Custom Sort Function&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;As mentioned earlier, the sort() function can accept a custom comparison function as an argument.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
sort(compareFn?: ((a: never, b: never) =&amp;gt; number) | undefined): never[]
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The comparison function is used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they are equal, and a positive value otherwise. If the comparison function is omitted, the elements are sorted in ascending ASCII character order.
&lt;/p&gt;

&lt;p&gt;For example:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
[11, 2, 22, 1].sort((a, b) =&amp;gt; a - b);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;This code sorts an array in place. The method mutates the array and returns a reference to the same array.
&lt;/p&gt;

&lt;p&gt;So, what does all of this mean?
&lt;/p&gt;

&lt;p&gt;The custom comparison function has specific expectations. It requires you to return certain values:
&lt;/p&gt;

&lt;p&gt;- -1: if the value on the left is less than the value on the right.
  &lt;br&gt;
  - 0: if the value on the left is equal to the value on the right.
  &lt;br&gt;
  - 1: if the value on the left is greater than the value on the right.
&lt;/p&gt;

&lt;p&gt;In simpler terms, returning -1 moves the item to the left (before the compared value), returning 0 keeps it in place, and returning 1 moves the item to the right (after the compared value).
&lt;/p&gt;

&lt;p&gt;Now let's explore some examples to understand how it works.
&lt;/p&gt;

&lt;p&gt;Referring to the previous example where we struggled to sort an array of numbers, we can fix this by using a custom comparison function:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const numberSortFn = (a, b) =&amp;gt; {
if (a &amp;lt; b) {
return -1;
} else if (a === b) {
return 0;
} else {
return 1;
}
};
const numbers = [9, 3, 12, 11, 40, 28, 5];
const sortedNumbers = numbers.sort(numberSortFn);
console.log(sortedNumbers);
// Output:
[3, 5, 9, 11, 12, 28, 40];
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;As you can see, the array is now sorted in numerical ascending order as we expected. The reason it works differently is because the less than operator now compares the values as numbers rather than strings.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;Other Uses of the Custom Comparison Function&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;In addition to sorting arrays of numbers, you can also utilize the custom comparison function to sort objects based on their properties. Let's explore an example of sorting an array of objects (books) based on their year of publication.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const books = [
{ title: "Book A", year: 2010 },
{ title: "Book B", year: 2005 },
{ title: "Book C", year: 2018 },
];
const booksSortedByYearAsc = books.sort((a, b) =&amp;gt; a.year - b.year);
console.log(booksSortedByYearAsc);
// Output:
[
{ title: "Book B", year: 2005 },
{ title: "Book A", year: 2010 },
{ title: "Book C", year: 2018 },
];


```


&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In this example, we provide a custom comparison function that compares the objects based on their `.year` property. By subtracting `b.year` from `a.year`, we can achieve ascending order sorting based on the year of publication.
&lt;/p&gt;

&lt;p&gt;This technique allows you to sort objects in arrays based on any property you choose. You simply need to modify the comparison function accordingly to compare the desired properties.
&lt;/p&gt;

&lt;p&gt;By utilizing custom comparison functions, you gain flexibility in sorting arrays of various data types and objects based on specific criteria.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;Sorting based on the content of the string&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;Let's take our sorting capabilities a step further. Imagine we have a list of attendees at a seminar, and we want to generate a register. However, we want to prioritize the doctors and have them listed at the top, as they are the keynote speakers.
&lt;/p&gt;

&lt;p&gt;We can achieve this using a custom comparison function:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const names = ["Mike Smith", "Dr. Johnson", "John Doe", "Dr. Williams"];
names.sort((a, b) =&amp;gt; {
if (a.startsWith("Dr.") &amp;amp;&amp;amp; !b.startsWith("Dr.")) {
return -1;
} else if (!a.startsWith("Dr.") &amp;amp;&amp;amp; b.startsWith("Dr.")) {
return 1;
} else {
return a.localeCompare(b); // sort alphabetically
}
});
console.log(names);
// Output:
["Dr. Johnson", "Dr. Williams", "John Doe", "Mike Smith"];
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In this example, we define a custom comparison function that checks if a string starts with "Dr." or not. If the first string starts with "Dr." and the second one does not, we return -1, indicating that the first string should be placed before the second string in the sorted array. Conversely, if the first string does not start with "Dr." and the second one does, we return 1 to indicate the opposite order.
&lt;/p&gt;

&lt;p&gt;For cases where neither string has "Dr." at the beginning, we resort to using the `localeCompare` function. This function performs an alphabetical comparison using Unicode values, similar to the default behavior discussed earlier in this article.
&lt;/p&gt;

&lt;p&gt;By incorporating custom comparison logic, you can prioritize specific patterns or values in your sorting process, enabling you to achieve more specialized sorting results based on the content of the strings.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;Strings of Numbers and Letters&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;Suppose you have an array that contains a mixture of numbers and letters, and you want to sort it in a specific way. Your goal is to have the numbers appear before the letters, and within each group, you want the elements to be sorted numerically and alphabetically, respectively. Here's how you can achieve that using a custom comparison function:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const items = ["b", "3", "a", "2", "c", "1"];
&lt;/pre&gt;

&lt;p&gt;items.sort((a, b) =&amp;gt; { const aIsNumber = !isNaN(a); const bIsNumber = !isNaN(b); if (aIsNumber &amp;amp;&amp;amp; !bIsNumber) { return -1; // Numbers should be sorted before letters } else if (!aIsNumber &amp;amp;&amp;amp; bIsNumber) { return 1; // Letters should be sorted after numbers } else if (aIsNumber &amp;amp;&amp;amp; bIsNumber) { return a - b; // Sort numbers numerically } else { return a.localeCompare(b); // Sort letters alphabetically } }); console.log(items) // Output: ["1", "2", "3", "a", "b", "c"];
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In this example, we first determine whether each value is a number or not using the 
  &lt;code&gt;isNaN()
  &lt;/code&gt; function. By checking if the negation of 
  &lt;code&gt;isNaN()
  &lt;/code&gt; is `true`, we can identify if the value is a number.
&lt;/p&gt;

&lt;p&gt;Based on this information, we apply the following logic:
&lt;/p&gt;

&lt;p&gt;- If `a` is a number and `b` is not a number, we return -1 to indicate that numbers should be sorted before letters.
  &lt;br&gt;
  - If `a` is not a number and `b` is a number, we return 1 to indicate that letters should be sorted after numbers.
  &lt;br&gt;
  - If both `a` and `b` are numbers, we subtract `b` from `a` (`a - b`). This allows us to sort the numbers numerically by comparing the numeric values.
  &lt;br&gt;
  - If none of the above conditions are met, we resort to using `localeCompare()` to sort the letters alphabetically.
&lt;/p&gt;

&lt;p&gt;By incorporating this custom comparison logic, we can achieve the desired sorting order, where numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;strong&gt;Strings of Numbers and Letters&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;Suppose you have an array that contains a mixture of numbers and letters, and you want to sort it in a specific way. Your goal is to have the numbers appear before the letters, and within each group, you want the elements to be sorted numerically and alphabetically, respectively. Here's how you can achieve that using a custom comparison function:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const items = ["b", "3", "a", "2", "c", "1"];
items.sort((a, b) =&amp;gt; {
const aIsNumber = !isNaN(a);
const bIsNumber = !isNaN(b);
if (aIsNumber &amp;amp;&amp;amp; !bIsNumber) {
return -1; // Numbers should be sorted before letters
} else if (!aIsNumber &amp;amp;&amp;amp; bIsNumber) {
return 1; // Letters should be sorted after numbers
} else if (aIsNumber &amp;amp;&amp;amp; bIsNumber) {
return a - b; // Sort numbers numerically
} else {
return a.localeCompare(b); // Sort letters alphabetically
}
})
// Output:
["1", "2", "3", "a", "b", "c"];
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In this example, we first determine whether each value is a number or not using the 
  &lt;code&gt;isNaN()
  &lt;/code&gt; function. By checking if the negation of 
  &lt;code&gt;isNaN()
  &lt;/code&gt; is `true`, we can identify if the value is a number.
&lt;/p&gt;

&lt;p&gt;Based on this information, we apply the following logic:
&lt;/p&gt;

&lt;p&gt;- If `a` is a number and `b` is not a number, we return -1 to indicate that numbers should be sorted before letters.
  &lt;br&gt;
  - If `a` is not a number and `b` is a number, we return 1 to indicate that letters should be sorted after numbers.
  &lt;br&gt;
  - If both `a` and `b` are numbers, we subtract `b` from `a` (`a - b`). This allows us to sort the numbers numerically by comparing the numeric values.
  &lt;br&gt;
  - If none of the above conditions are met, we resort to using `localeCompare()` to sort the letters alphabetically.
&lt;/p&gt;

&lt;p&gt;By incorporating this custom comparison logic, we can achieve the desired sorting order, where numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively.
&lt;/p&gt;

&lt;p&gt;In the code snippet provided, there is a custom comparison function used to sort an array containing both numbers and letters. The logic is designed to prioritize sorting based on the type (number or letter) and then further refine the order within each group. Let's break down the logic step by step:
&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Checking if values are numbers: The 
      &lt;code&gt;isNaN()
      &lt;/code&gt; function is used to check if a value is not a number. By negating the result using the logical NOT operator 
      &lt;code&gt;(!)
      &lt;/code&gt;, 
      &lt;code&gt;aIsNumber
      &lt;/code&gt; and 
      &lt;code&gt;bIsNumber
      &lt;/code&gt; are set to true if the corresponding value is a number and false otherwise.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Sorting numbers before letters: The first if statement checks if a is a number (
      &lt;code&gt;aIsNumber
      &lt;/code&gt; is true) and b is not a number (
      &lt;code&gt;bIsNumber
      &lt;/code&gt; is false). In this case, we return -1 to indicate that a should come before b in the sorted order.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Sorting letters after numbers: The second if statement checks if a is not a number (
      &lt;code&gt;aIsNumber
      &lt;/code&gt; is false) and b is a number (
      &lt;code&gt;bIsNumber
      &lt;/code&gt; is true). Here, we return 1 to indicate that b should come after a in the sorted order.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Sorting numbers numerically: The third if statement checks if both a and b are numbers (aIsNumber and 
      &lt;code&gt;bIsNumber
      &lt;/code&gt; are both true). In this case, we perform a numeric comparison by subtracting b from a. The result of this subtraction determines the relative order of the numbers.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Sorting letters alphabetically: If none of the previous conditions are met, it means both a and b are strings (letters). We then use the 
      &lt;code&gt;localeCompare()
      &lt;/code&gt; function to perform an alphabetical comparison and determine the order of the letters.
    &lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By applying this custom comparison logic, the array items is sorted in the desired order. Numbers appear before letters, and within each group, the elements are sorted numerically and alphabetically, respectively. The resulting sorted array is 
  &lt;code&gt;["1", "2", "3", "a", "b", "c"]
  &lt;/code&gt;.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;Explanation of Sorting in Descending Order
&lt;/h3&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;In the code snippet provided, the goal is to sort an array of tastes in descending order. Instead of using the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; approach, the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; function is used with a custom comparison function to achieve the desired result. Let's break down the code:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
javascript
const tastes = [
"Margherita",
"Napoletana",
"Quattro Formaggi",
"Primavera",
"Marinara",
"Boscaiola",
"Bufala",
];
const sortedArray = tastes.sort((a, b) =&amp;gt; b.localeCompare(a));
console.log(sortedArray);
// Output:
["Quattro Formaggi", "Primavera", "Napoletana", "Margherita", "Marinara", "Bufala", "Boscaiola"]
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;sort()
  &lt;/code&gt; function takes a comparison function as an argument, which defines the custom sorting logic. In this case, the comparison function 
  &lt;code&gt;(a, b) =&amp;gt; b.localeCompare(a)
  &lt;/code&gt; is used.
&lt;/p&gt;

&lt;p&gt;By default, the 
  &lt;code&gt;localeCompare()
  &lt;/code&gt; function compares strings in ascending alphabetical order. However, to achieve descending order, the comparison is inverted by comparing `b` to `a` instead of the usual `a` to `b`. This reversal of the operands ensures that the comparison is performed in the desired descending order.
&lt;/p&gt;

&lt;p&gt;As a result, the array `tastes` is sorted in descending order, and the sorted array `sortedArray` contains the elements 
  &lt;code&gt;["Napoletana", "Quattro Formaggi", "Marinara", "Margherita", "Primavera", "Bufala", "Boscaiola"]`
  &lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;It's worth noting that this approach works specifically for sorting an array of strings. If you're sorting numbers or objects based on a specific property, the comparison logic will differ.
&lt;/p&gt;

&lt;p&gt;When it comes to the performance of sorting arrays, there are several factors to consider, including the JavaScript engine, array size, and complexity of the custom sorting function. The performance can vary based on these factors.
&lt;/p&gt;

&lt;p&gt;In general, the built-in 
  &lt;code&gt;sort()
  &lt;/code&gt; method tends to be highly optimized by ECMAScript implementations, making it very efficient for most sorting scenarios. It utilizes internal algorithms that are designed to handle a wide range of use cases and perform well in various scenarios.
&lt;/p&gt;

&lt;p&gt;On the other hand, using a custom comparison function with the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; method introduces additional complexity to the sorting process. The execution time of the custom function can impact the overall performance, especially for large arrays or if the custom logic involves complex computations.
&lt;/p&gt;

&lt;p&gt;In the example you provided, sorting an array of 100 words in ascending order, the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; implementation was faster than the default 
  &lt;code&gt;sort()
  &lt;/code&gt; method. However, when sorting in descending order, the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; chaining was faster than the 
  &lt;code&gt;sort(compareFn)
  &lt;/code&gt; approach.
&lt;/p&gt;

&lt;p&gt;The difference in execution time between the two approaches may seem small (e.g., 6ms), but it can become more significant as the array size grows or when dealing with more complex sorting requirements.
&lt;/p&gt;

&lt;p&gt;As a general guideline, it's recommended to use the default 
  &lt;code&gt;sort()
  &lt;/code&gt; method whenever possible, as it is optimized and performs well for most use cases. Reserve the use of custom comparison functions for situations where you have specific and complex sorting requirements that cannot be achieved with the default sorting behavior.
&lt;/p&gt;

&lt;p&gt;Ultimately, it's important to consider the trade-off between customization and performance when deciding which approach to use for sorting arrays.
&lt;/p&gt;



&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;That concludes the discussion on the JavaScript 
  &lt;code&gt;sort()
  &lt;/code&gt; function. Throughout the article, we covered the basics of the 
  &lt;code&gt;sort()
  &lt;/code&gt; function, delved into its inner workings, and explored various use cases and examples to illustrate its versatility. We also discussed some considerations and performance implications when working with the 
  &lt;code&gt;sort()
  &lt;/code&gt; function.
&lt;/p&gt;

&lt;p&gt;I'm glad you found the article helpful in gaining a better understanding of the 
  &lt;code&gt;sort()
  &lt;/code&gt; function and its capabilities. If you have any more questions or need further assistance, feel free to ask. Additionally, you can follow me on Twitter at gWeaths to stay updated on any future articles or information.
&lt;/p&gt;

&lt;p&gt;Thank you for your engagement, and happy coding!
&lt;/p&gt;



</description>
      <category>javascript</category>
      <category>development</category>
    </item>
    <item>
      <title>The Payment Request API: Revolutionizing Online Payments (Part 2)</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Mon, 05 Jun 2023 15:31:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/the-payment-request-api-revolutionizing-online-payments-part-2-6cn</link>
      <guid>https://dev.to/salvietta150x40/the-payment-request-api-revolutionizing-online-payments-part-2-6cn</guid>
      <description>&lt;p&gt;our case, for testing purposes to simulate transactions without making real payments.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;apiVersion: 2
  &lt;/code&gt; and 
  &lt;code&gt;apiVersionMinor: 0
  &lt;/code&gt; specify the version of the Google Pay API being used. In this case, we use version 2.0.
&lt;/p&gt;

&lt;p&gt;We proceed by adding the 
  &lt;code&gt;merchantInfo
  &lt;/code&gt; object specifying information about the merchant accepting the payment.
&lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;merchantIdentifier
  &lt;/code&gt;, which we specified earlier, is a unique identifier assigned to the merchant by Google Pay.
&lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;merchantName
  &lt;/code&gt; specifies the name of the merchant.
&lt;/p&gt;

&lt;p&gt;Here's the code:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;{&lt;br&gt;supportedMethods: ['https://google.com/pay'],&lt;br&gt;        data: {&lt;br&gt;        environment: "TEST",&lt;br&gt;                apiVersion: 2,&lt;br&gt;                apiVersionMinor: 0,&lt;br&gt;                merchantInfo: {&lt;br&gt;                merchantIdentifier: '12345678901234567890',&lt;br&gt;                        merchantName: "Example Merchant"&lt;br&gt;                        },&lt;br&gt;                allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],&lt;br&gt;                },&lt;br&gt;        },&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In summary, this code block sets up the configuration for integrating Google Pay as a supported payment method. It includes specifying the environment, API version, merchant information, and allowed payment methods for Google Pay. This configuration enables users to choose Google Pay as a payment option when making a transaction on your web application.
&lt;/p&gt;

&lt;p&gt;The next step is the configuration of the 
  &lt;code&gt;paymentOptions
  &lt;/code&gt; object, with which you can customize the behavior and appearance of the payment request to suit your specific needs. These options allow you to collect the necessary information from the payer and facilitate the payment process.
&lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;paymentOptions
  &lt;/code&gt; object is an object that contains various options or settings related to the payment request. It provides configuration for how the payment request should be displayed and what information it should collect from the payer. Let's go through each property of the paymentOptions object:
&lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;requestPayerName
  &lt;/code&gt;:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This property determines whether the payment request should prompt the user to provide their name.&lt;/li&gt;
  &lt;li&gt;If set to true, the payment sheet will include a field where the payer can enter their name.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;requestPayerEmail:
  &lt;/code&gt;
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This property specifies whether the payment request should prompt the user to enter their email address.&lt;/li&gt;
  &lt;li&gt;When set to true, the payment sheet will include a field where the payer can enter their email address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;requestPayerPhone:
  &lt;/code&gt;
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This property indicates whether the payment request should ask the user to provide their phone number.&lt;/li&gt;
  &lt;li&gt;If set to true, the payment sheet will include a field for the payer to enter their phone number.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;requestShipping:
  &lt;/code&gt;
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This property determines whether the payment request should include a section for the payer to enter their shipping address.&lt;/li&gt;
  &lt;li&gt;If set to true, the payment sheet will prompt the user to enter their shipping address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;
  &lt;code&gt;shippingType:
  &lt;/code&gt;
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;This property specifies the type of shipping requested from the user.&lt;/li&gt;
  &lt;li&gt;In this case, the value is set to "shipping", indicating that the requested shipping is for physical goods to be delivered to the payer's address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The next major change to the previous code, is the addition of used to retrieve an HTML element from the DOM with the id attribute set to "response".
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const response = document.getElementById("response");
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The purpose of this line is to obtain a reference to an element in the HTML document where you want to display the response or status of the payment request. By using 
  &lt;code&gt;document.getElementById
  &lt;/code&gt;("response"), you can access and manipulate the content of that specific element.
&lt;/p&gt;

&lt;p&gt;After retrieving the element using 
  &lt;code&gt;document.getElementById
  &lt;/code&gt;("response"), the reference is stored in the 
  &lt;code&gt;response
  &lt;/code&gt; constant. Later in the code, the content of this element is updated based on the outcome of the payment request. For example, if the payment is successful, a text is displayed within the 
  &lt;code&gt;response
  &lt;/code&gt; element.
&lt;/p&gt;

&lt;p&gt;We are now going to modify the code that sets up an event listener for a button click and shows a payment request sheet to the user, handles the payment response, and provides appropriate feedback messages to the user based on the outcome of the payment process.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
// Add an event listener to the paymentButton
paymentButton.addEventListener('click', async () =&amp;gt; {
try {
// Show the payment request sheet to the user
const paymentResponse = await paymentRequest.show();
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In this part, an event listener is added to the paymentButton element. It listens for a '&lt;strong&gt;click&lt;/strong&gt;' event and executes the callback function when the button is clicked. The callback function is defined as an asynchronous function, denoted by the 
  &lt;code&gt;async
  &lt;/code&gt; keyword. Inside the callback function, the code attempts to show the payment request sheet to the user by calling 
  &lt;code&gt;paymentRequest.show()
  &lt;/code&gt;. This function displays a sheet or dialog where the user can enter their payment information.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;// Process the payment response&lt;br&gt;if (paymentResponse) {&lt;br&gt;// If a payment response is received&lt;br&gt;await paymentResponse.complete('success'); // Complete the payment&lt;br&gt;        await processPaymentResponse(paymentResponse); // Process the payment response&lt;br&gt;        response.innerText = 'thanks for your purchase'; // Display a success message&lt;br&gt;        } else {&lt;br&gt;// If the payment request is canceled&lt;br&gt;response.innerText = 'Payment request canceled.'; // Display a cancellation message&lt;br&gt;        }&lt;br&gt;} catch (error) {&lt;br&gt;// If an error occurs during the payment request&lt;br&gt;console.error('Payment request failed:', error); // Log the error to the console&lt;br&gt;        response.innerText = 'Sorry, something went wrong.'; // Display an error message&lt;br&gt;        }&lt;br&gt;});&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;After showing the payment request sheet, the code checks if a 
  &lt;code&gt;paymentResponse
  &lt;/code&gt; object is received. If a response is present, it means the user has completed the payment process.
&lt;/p&gt;

&lt;p&gt;In the case of a successful payment response, the code proceeds to complete the payment by calling 
  &lt;code&gt;paymentResponse.complete('success')
  &lt;/code&gt;. This informs the payment system that the payment was successful. Then, it calls the 
  &lt;code&gt;processPaymentResponse
  &lt;/code&gt; function, passing the paymentResponse object as an argument. This function is responsible for handling the payment response and performing any necessary actions based on the response.
&lt;/p&gt;

&lt;p&gt;Finally, it updates the response element with a success message.
&lt;/p&gt;

&lt;p&gt;If the payment request is canceled (no paymentResponse object), the code updates the response element with a cancellation message.
&lt;/p&gt;

&lt;p&gt;If an error occurs during the payment request, the code catches the error in the catch block. It logs the error message to the console using console.error and updates the response element with an error message.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;// Define a function to process the payment response&lt;br&gt;async function processPaymentResponse(paymentResponse) {&lt;br&gt;// Handle the payment response here&lt;br&gt;// Implement the necessary logic based on the response&lt;br&gt;  console.log('Processing payment response:', paymentResponse);&lt;br&gt;// ...&lt;br&gt;} &lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;processPaymentResponse
  &lt;/code&gt; function is defined separately, outside the event listener. It is an asynchronous function that takes the 
  &lt;code&gt;paymentResponse
  &lt;/code&gt; object as an argument. This function can be implemented to handle the payment response as needed. In the code provided, it logs the 
  &lt;code&gt;paymentResponse
  &lt;/code&gt; object to the console.
&lt;/p&gt;

&lt;p&gt;Clearly, you can modify this function to perform any specific logic required for processing the payment response.
&lt;/p&gt;

&lt;p&gt;I am sure this is the part that many of you have been waiting for, a demo to try it out for yourself: &lt;strong&gt;feel free to try out this &lt;a href="https://codepen.io/salvietta150x40/pen/ZEmYWBe" title="The Payment Request API: Revolutionizing Online Payments"&gt;CodePen&lt;/a&gt;.&lt;/strong&gt;
&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>api</category>
      <category>development</category>
    </item>
    <item>
      <title>The Payment Request API: Revolutionizing Online Payments (Part 1)</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Sun, 04 Jun 2023 13:15:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/the-payment-request-api-revolutionizing-online-payments-part-1-3ifj</link>
      <guid>https://dev.to/salvietta150x40/the-payment-request-api-revolutionizing-online-payments-part-1-3ifj</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Zvwhq_xl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2294/960-400/payment-api-development-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Zvwhq_xl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2294/960-400/payment-api-development-impjpg.webp" alt="Streamlining Payment Processes for Seamless Transactions" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into the intricacies of this powerful API and explore how it simplifies the payment experience for both users and merchants.
&lt;/p&gt;

&lt;p&gt;The Payment Request API serves as a bridge between merchants and users, enabling seamless and secure payments. With its integration into modern browsers, the API allows websites to request payment information from users, such as credit card details or digital wallet credentials, in a standardized and user-friendly manner. By eliminating the need for manual form-filling and offering a consistent payment interface across different platforms, the API significantly enhances the checkout process.
&lt;/p&gt;

&lt;p&gt;To illustrate the simplicity of integrating the Payment Request API, let's consider an example. The following code demonstrates how to create a &lt;strong&gt;basic payment &lt;/strong&gt;request:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;THE HTML&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;!--The button with the id paymentButton triggers the payment process when clicked.--&amp;gt;
&amp;lt;button id="paymentButton"&amp;gt;Pay Now&amp;lt;/button&amp;gt; 
&amp;lt;div id="response"&amp;gt;We do not charge you anything, it is just a test!&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;THE JAVASCRIPT&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;// Define the supported payment methods&lt;br&gt;const supportedPaymentMethods = [&lt;br&gt;  {&lt;br&gt;    supportedMethods: ['basic-card'],&lt;br&gt;    data: {&lt;br&gt;      supportedNetworks: ['visa', 'mastercard'],&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;  {&lt;br&gt;    supportedMethods: ['https://google.com/pay'],&lt;br&gt;    data: {&lt;br&gt;      merchantIdentifier: '0123456789',&lt;br&gt;      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;];&lt;br&gt;// Define the payment details&lt;br&gt;const paymentDetails = {&lt;br&gt;  total: {&lt;br&gt;    label: 'Total',&lt;br&gt;    amount: {&lt;br&gt;      currency: 'USD',&lt;br&gt;      value: '100.00',&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;  displayItems: [&lt;br&gt;    {&lt;br&gt;      label: 'Product A',&lt;br&gt;      amount: {&lt;br&gt;        currency: 'USD',&lt;br&gt;        value: '50.00',&lt;br&gt;      },&lt;br&gt;    },&lt;br&gt;    {&lt;br&gt;      label: 'Product B',&lt;br&gt;      amount: {&lt;br&gt;        currency: 'USD',&lt;br&gt;        value: '50.00',&lt;br&gt;      },&lt;br&gt;    },&lt;br&gt;  ],&lt;br&gt;};&lt;br&gt;// Create a payment request&lt;br&gt;const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);&lt;br&gt;// Display the payment sheet when the user clicks a button&lt;br&gt;const paymentButton = document.getElementById('paymentButton');&lt;br&gt;paymentButton.addEventListener('click', async () =&amp;gt; {&lt;br&gt;  try {&lt;br&gt;// Show the payment request sheet to the user&lt;br&gt;    const paymentResponse = await paymentRequest.show();&lt;br&gt;// Process the payment response&lt;br&gt;    await processPaymentResponse(paymentResponse);&lt;br&gt;  } catch (error) {&lt;br&gt;    console.error('Error processing payment:', error);&lt;br&gt;  }&lt;br&gt;});&lt;br&gt;// Process the payment response      &lt;br&gt;async function processPaymentResponse(paymentResponse) {&lt;br&gt;// Implement your logic to handle the payment response here        &lt;br&gt;// This function will be called when the user completes the payment      &lt;br&gt;}&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;And now, let's have a look at the last part of the code, explaining the code step by step.
&lt;/p&gt;

&lt;p&gt;First of all, we create a Payment Request Object using the 
  &lt;code&gt;PaymentRequest() 
  &lt;/code&gt; constructor.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;PaymentRequest 
  &lt;/code&gt; object is created with two parameters: 
  &lt;code&gt;supportedPaymentMethods 
  &lt;/code&gt; and 
  &lt;code&gt;paymentDetails 
  &lt;/code&gt;. The 
  &lt;code&gt;supportedPaymentMethods 
  &lt;/code&gt; is an array that defines, as suggested, the supported payment methods, such as credit cards or third-party payment providers.
&lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;paymentDetails 
  &lt;/code&gt; object specifies the details of the payment, including the total amount and individual items.
&lt;/p&gt;

&lt;p&gt;Let's continue:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;const paymentButton = document.getElementById('paymentButton');&lt;br&gt;// Display the payment sheet when the user clicks a button&lt;br&gt;paymentButton.addEventListener('click', async () =&amp;gt; {&lt;br&gt;  try {&lt;br&gt;// Show the payment request sheet to the user&lt;br&gt;    const paymentResponse = await paymentRequest.show();&lt;br&gt;// Process the payment response&lt;br&gt;    await processPaymentResponse(paymentResponse);&lt;br&gt;  } catch (error) {&lt;br&gt;    console.error('Error processing payment:', error);&lt;br&gt;  }&lt;br&gt;});&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;In the first line, we define the 
  &lt;code&gt;paymentButton 
  &lt;/code&gt; variable by retrieving the element using 
  &lt;code&gt;document.getElementById 
  &lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;Then, an event listener is added to a button with the id 
  &lt;code&gt;paymentButton 
  &lt;/code&gt;. When the button is clicked, the 
  &lt;code&gt;click 
  &lt;/code&gt; event is triggered. Inside the event handler, the 
  &lt;code&gt;show() 
  &lt;/code&gt; method of the paymentRequest object is called to display the payment sheet to the user. This method returns a promise that resolves with a 
  &lt;code&gt;PaymentResponse 
  &lt;/code&gt; object when the user completes or cancels the payment.
&lt;/p&gt;

&lt;p&gt;If the payment is completed, the 
  &lt;code&gt;processPaymentResponse() 
  &lt;/code&gt; function is called with the 
  &lt;code&gt;paymentResponse 
  &lt;/code&gt; as an argument to handle the payment response. If an error occurs during the payment process, it is caught in the catch block, and an error message is logged to the console.
&lt;/p&gt;

&lt;p&gt;In the following code, we define the supported methods:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;// Define the supported payment methods&lt;br&gt;const supportedPaymentMethods = [&lt;br&gt;  {&lt;br&gt;    supportedMethods: ['basic-card'],&lt;br&gt;    data: {&lt;br&gt;      supportedNetworks: ['visa', 'mastercard'],&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;  {&lt;br&gt;    supportedMethods: ['https://google.com/pay'],&lt;br&gt;    data: {&lt;br&gt;      merchantIdentifier: '0123456789',&lt;br&gt;      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;];&lt;br&gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;supportedPaymentMethods 
  &lt;/code&gt; variable is an array that defines the supported payment methods. In this example, two methods are defined: 
  &lt;code&gt;basic-card 
  &lt;/code&gt; and 
  &lt;code&gt;https://google.com/pay 
  &lt;/code&gt;. The 
  &lt;code&gt;basic-card 
  &lt;/code&gt; method supports credit cards with the &lt;strong&gt;visa&lt;/strong&gt; and &lt;strong&gt;mastercard&lt;/strong&gt; networks. The 
  &lt;code&gt;https://google.com/pay 
  &lt;/code&gt; method is a custom payment method provided by Google Pay, and it requires the merchant identifier and the allowed payment methods to be specified.
&lt;/p&gt;

&lt;p&gt;Clearly the choice of supported payment methods depends on your specific requirements and the target audience of your application or website. Here are some commonly used payment methods that you may consider adding to the 
  &lt;code&gt;supportedPaymentMethods 
  &lt;/code&gt; array:
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Credit Cards:&lt;/strong&gt;
  &lt;br&gt;
  ' 
  &lt;code&gt;basic-card 
  &lt;/code&gt;': This method supports basic credit card payments. It is widely supported and allows users to enter their card details manually.
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Digital Wallets:&lt;/strong&gt;
  &lt;br&gt;
  &lt;code&gt;https://google.com/pay 
  &lt;/code&gt;: This method enables users to pay using Google Pay. It requires the merchant identifier and supports various payment methods provided by Google Pay.
  &lt;br&gt;
  &lt;code&gt;https://apple.com/apple-pay 
  &lt;/code&gt;: This method enables users to pay using Apple Pay. It requires additional configuration and supports Apple Pay as a payment method.
  &lt;br&gt;
  ' 
  &lt;code&gt;https://www.paypal.com/webapps/mpp/paypal-checkout 
  &lt;/code&gt;`: This method integrates PayPal Checkout, allowing users to pay with their PayPal accounts.
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Bank Transfers:&lt;/strong&gt;
  &lt;br&gt;
  &lt;code&gt;https://secure.checkout.example/bank 
  &lt;/code&gt;: This method allows users to initiate bank transfers directly from their bank accounts.
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Cryptocurrencies:&lt;/strong&gt;
  &lt;br&gt;
  &lt;code&gt;https://example.com/bitcoin 
  &lt;/code&gt;: This method supports payments using cryptocurrencies like Bitcoin or Ethereum. It requires integration with a cryptocurrency payment processor.
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Local Payment Methods:&lt;/strong&gt;
  &lt;br&gt;
  &lt;code&gt;https://example.com/local-payment 
  &lt;/code&gt;: This method represents a custom local payment method specific to your region or target audience. It would require integration with a local payment provider.
&lt;/p&gt;

&lt;p&gt;It's important to note that the availability and support for these payment methods may vary depending on the payment processor or platform you are using. You should consult the documentation of your payment provider or platform to identify the specific supported payment methods they offer.
&lt;/p&gt;



&lt;p&gt;Consistent with the choice to use 
  &lt;code&gt;https://google.com/pay 
  &lt;/code&gt;, the 
  &lt;code&gt;allowedPaymentMethods 
  &lt;/code&gt; property is set to 
  &lt;code&gt;['TOKENIZED_CARD', 'CARD'] 
  &lt;/code&gt;. These values represent the specific payment methods allowed within the &lt;strong&gt;Google Pay integration.&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;allowedPaymentMethods 
  &lt;/code&gt; property helps define the available options within a payment method. For example, it could be used to differentiate between credit card payments and tokenized card payments (where the card details are stored securely by the payment provider).
&lt;/p&gt;

&lt;p&gt;By specifying the allowed payment methods, you can control the options presented to the user during the payment process. It allows you to tailor the payment experience based on your specific integration requirements and the capabilities of the payment provider or platform you are working with.
&lt;/p&gt;

&lt;p&gt;In the code that follows, we will define the payment details:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;// Define the payment details&lt;br&gt;const paymentDetails = {&lt;br&gt;  total: {&lt;br&gt;    label: 'Total',&lt;br&gt;    amount: {&lt;br&gt;      currency: 'USD',&lt;br&gt;      value: '100.00',&lt;br&gt;    },&lt;br&gt;  },&lt;br&gt;  displayItems: [&lt;br&gt;    {&lt;br&gt;      label: 'Product A',&lt;br&gt;      amount: {&lt;br&gt;        currency: 'USD',&lt;br&gt;        value: '50.00',&lt;br&gt;      },&lt;br&gt;    },&lt;br&gt;    {&lt;br&gt;      label: 'Product B',&lt;br&gt;      amount: {&lt;br&gt;        currency: 'USD',&lt;br&gt;        value: '50.00',&lt;br&gt;      },&lt;br&gt;    },&lt;br&gt;  ],&lt;br&gt;};&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;As the 
  &lt;code&gt;paymentDetails 
  &lt;/code&gt; variable name suggested, it specifies the details of the payment. It includes a 
  &lt;code&gt;total 
  &lt;/code&gt; object that defines the total amount to be paid. In this case, the total is $100.00 USD. The 
  &lt;code&gt;displayItems 
  &lt;/code&gt; array contains individual items included in the payment, such as 'Product A' and 'Product B', each with a value of $50.00 USD.
&lt;/p&gt;

&lt;p&gt;Overall, this code sets up a payment request with supported payment methods and payment details, shows a payment sheet when a button is clicked, and handles the payment response.
&lt;/p&gt;

&lt;p&gt;When the 
  &lt;code&gt;paymentButton 
  &lt;/code&gt; is clicked, the click event handler is triggered. It calls the 
  &lt;code&gt;show() 
  &lt;/code&gt; method on the 
  &lt;code&gt;paymentRequest 
  &lt;/code&gt; object, which displays the payment sheet to the user. The user will be presented with a UI to choose a payment method and enter payment details.
&lt;/p&gt;

&lt;p&gt;If the user completes the payment, the 
  &lt;code&gt;show() 
  &lt;/code&gt; method will resolve with a 
  &lt;code&gt;PaymentResponse 
  &lt;/code&gt; object, which represents the user's payment authorization. This response is then passed to the 
  &lt;code&gt;processPaymentResponse() 
  &lt;/code&gt; function for further processing. The 
  &lt;code&gt;processPaymentResponse() 
  &lt;/code&gt; function is not shown in the code snippet you provided, but it would typically handle the payment response by sending it to a server for verification and processing the payment on the server-side.
&lt;/p&gt;

&lt;p&gt;On the other hand, if the user cancels the payment or an error occurs during the payment process, the 
  &lt;code&gt;catch 
  &lt;/code&gt; block will be executed, and an error message will be logged to the console.
&lt;/p&gt;

&lt;p&gt;Overall, this code demonstrates a &lt;strong&gt;basic implementation&lt;/strong&gt; of the Payment Request API, where the user is presented with a payment sheet, and the payment response is processed asynchronously. The specific implementation of the 
  &lt;code&gt;processPaymentResponse() 
  &lt;/code&gt; function and the subsequent steps for handling the payment will depend on the requirements of the application or website where this code is being used.
&lt;/p&gt;

&lt;p&gt;By utilizing the Payment Request API, websites can streamline the payment experience for users. It provides a standardized and user-friendly interface, supports multiple payment methods, and enhances security through tokenization.
&lt;/p&gt;

&lt;p&gt;In addiction, here are some useful links to the Mozilla Developer Network (MDN) documentation that provide more detailed information about the Payment Request API, including browser support:
&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API" rel="nofollow"&gt;Payment Request API - MDN Web Docs&lt;/a&gt;: This page provides an overview of the Payment Request API, including its purpose, browser compatibility, and key concepts. It covers the basic usage of the API and provides examples to help you get started.&lt;/li&gt;
  &lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest" rel="nofollow"&gt;PaymentRequest - MDN Web Docs&lt;/a&gt;: This is the specific documentation for the PaymentRequest interface. It explains the properties, methods, and events associated with the PaymentRequest object. It also provides examples and usage guidelines for creating payment requests.&lt;/li&gt;
  &lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse" rel="nofollow"&gt;PaymentResponse - MDN Web Docs&lt;/a&gt;: This page focuses on the PaymentResponse interface, which represents the user's response to a payment request. It explains the properties and methods available on the PaymentResponse object and provides examples of how to handle and process the payment response.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Additionally, you can refer to the &lt;a href="https://caniuse.com/payment-request" rel="nofollow"&gt;Can I use&lt;/a&gt; website, which provides up-to-date information on browser support for the Payment Request API. It shows a detailed breakdown of support across different browsers and versions, helping you understand the compatibility of the API.
&lt;/p&gt;

&lt;p&gt;By referring to these resources, you'll be able to get a more comprehensive understanding of the Payment Request API, its usage, and the browser support you can expect.
&lt;/p&gt;

&lt;p&gt;In conclusion, the Payment Request API simplifies the payment process for users and merchants alike. By incorporating this API into their websites, businesses can create a seamless and secure payment experience, resulting in improved customer satisfaction and increased conversion rates.
&lt;/p&gt;

&lt;p&gt;In the next part of this series, we will explore &lt;a href="https://www.ma-no.org/en/programming/javascript/the-payment-request-api-revolutionizing-online-payments-part-2" title="advanced features and implementation best practices for harnessing the full potential of the Payment Request API"&gt;advanced features and how to process the payment response&lt;/a&gt;.
&lt;/p&gt;



&lt;p&gt;&lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
 &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>api</category>
      <category>development</category>
    </item>
    <item>
      <title>Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Fri, 02 Jun 2023 11:25:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/lets-create-a-color-picker-from-scratch-with-html5-canvas-javascript-and-css3-299b</link>
      <guid>https://dev.to/salvietta150x40/lets-create-a-color-picker-from-scratch-with-html5-canvas-javascript-and-css3-299b</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.ma-no.org%2Fcache%2Fgalleries%2Fcontents-731%2F960-400%2Fselector-canvas-de-html5-t1-imppng.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.ma-no.org%2Fcache%2Fgalleries%2Fcontents-731%2F960-400%2Fselector-canvas-de-html5-t1-imppng.webp" alt="Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images and text, can be drawn and manipulated with great flexibility and control.
&lt;/p&gt;

&lt;p&gt;Here are some key concepts about HTML5 Canvas:
&lt;/p&gt;

&lt;p&gt;1. &lt;strong&gt;Canvas element&lt;/strong&gt;: The 
  &lt;code&gt;&amp;lt;canvas&amp;gt;
  &lt;/code&gt; element is the base of the canvas on which the graphics are drawn. It is defined by HTML tags and can be sized using the `width` and `height` attributes. All graphic elements are drawn within this canvas.
&lt;/p&gt;

&lt;p&gt;2. &lt;strong&gt;Context: &lt;/strong&gt;The context (`&lt;em&gt;context&lt;/em&gt;`) is the object that provides methods and properties for drawing on the canvas. There are two types of context: &lt;strong&gt;2D&lt;/strong&gt; and &lt;strong&gt;WebG&lt;/strong&gt;L. For 2D graphics, the 2D context (`&lt;em&gt;context2d&lt;/em&gt;`) is used, which is more common. To access the 2D context, you use the
  &lt;code&gt; getContext('2d')
  &lt;/code&gt; method on the 
  &lt;code&gt;&amp;lt;canvas&amp;gt;
  &lt;/code&gt; element.
&lt;/p&gt;

&lt;p&gt;3. &lt;strong&gt;Coordinates and coordinate system&lt;/strong&gt;: The Canvas canvas uses a coordinate system in which `(&lt;em&gt;0, 0&lt;/em&gt;)` represents the upper left corner of the canvas and positive coordinates increase downwards and to the right. This means that the highest values of `x` are to the right and the highest values of `y` are to the bottom.
&lt;/p&gt;

&lt;p&gt;4. &lt;strong&gt;Drawing methods&lt;/strong&gt;: The 2D context provides a wide range of methods for drawing different graphical elements on the canvas, such as lines, rectangles, circles, curves, images and text. Some of the most common methods include 
  &lt;code&gt;fillRect()
  &lt;/code&gt;, 
  &lt;code&gt;strokeRect()
  &lt;/code&gt;, 
  &lt;code&gt;arc()
  &lt;/code&gt;, 
  &lt;code&gt;drawImage()
  &lt;/code&gt; y 
  &lt;code&gt;fillText()
  &lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;5. &lt;strong&gt;Styles and attributes&lt;/strong&gt;: The 2D context also allows you to set styles and attributes for graphic elements. You can set stroke and fill colours, line thickness, typography and other attributes that affect the visual appearance of graphics.
&lt;/p&gt;

&lt;p&gt;6. &lt;strong&gt;Animations&lt;/strong&gt;: One of the advantages of HTML5 Canvas is its ability to create fluid and dynamic animations. This can be achieved by using techniques such as periodic updating of the canvas, the use of the 
  &lt;code&gt;requestAnimationFrame()
  &lt;/code&gt; and the manipulation of the graphic elements in each frame.
&lt;/p&gt;

&lt;p&gt;HTML5 Canvas offers a wide range of creative possibilities and is used in many areas, such as online games, data visualisations, interactive applications and generative graphics. It is a powerful tool for web development and gives developers complete control over the graphical representation in the browser.
&lt;/p&gt;

&lt;p&gt;In this tutorial we are going to explain how to use the Canvas element to create a simple colour picker.
&lt;/p&gt;

&lt;p&gt;We start with the basic HTML code of the page:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta charset="utf-8" /&amp;gt;
&amp;lt;title&amp;gt;Colorpicker demo&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;We go on to define some CSS styles for the elements on the page. Styles are set for the body, a header (h2) and a Google Fonts font called "Open Sans" is imported.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;style&amp;gt;
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
h2 {
background-color: #dbdbdb;
margin: 0;
margin-bottom: 15px;
padding: 10px;
font-family: 'Open Sans';
}
/* Additional CSS for page elements */
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;We continue with our heading indicating the purpose of the colour picker.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;h2&amp;gt;Canvas Color Picker&amp;lt;/h2&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Then we create the two elements that will display the selected colour in &lt;strong&gt;RGBA&lt;/strong&gt; and &lt;strong&gt;HEX&lt;/strong&gt; format: the identifiers &lt;em&gt;txtRgba&lt;/em&gt; and &lt;em&gt;txtHex&lt;/em&gt; will be used to update the values later from the JavaScript code.
&lt;/p&gt;

&lt;pre&gt;
&amp;lt;label for="color-input" id="color-label" style="background-color: red"&amp;gt;&amp;lt;/label&amp;gt;
&amp;lt;input type="checkbox" id="color-input" checked&amp;gt;&amp;lt;/input&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Aquí creamos una etiqueta 
  &lt;code&gt;&amp;lt;label&amp;gt;
  &lt;/code&gt; con el identificador color-label. Esta etiqueta se utiliza como muestra visual del color seleccionado. También hay un 
  &lt;code&gt;&amp;lt;input&amp;gt;
  &lt;/code&gt; de tipo checkbox con el identificador &lt;strong&gt;color-input&lt;/strong&gt;, que se utiliza para controlar la visibilidad del selector de color.
&lt;/p&gt;

&lt;p&gt;Next we create a 
  &lt;code&gt;&amp;lt;div&amp;gt;
  &lt;/code&gt; container with the &lt;em&gt;colour-picker&lt;/em&gt; identifier, which contains two 
  &lt;code&gt;&amp;lt;canvas&amp;gt;
  &lt;/code&gt; elements. The first 
  &lt;code&gt;&amp;lt;canvas&amp;gt;
  &lt;/code&gt; with the colour-block identifier is used as the main canvas where the colour is selected. The second 
  &lt;code&gt;&amp;lt;canvas&amp;gt;
  &lt;/code&gt; with the &lt;em&gt;colour-strip&lt;/em&gt; identifier is used to display a colour strip to select the saturation component of the colour.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;div id="color-picker"&amp;gt;
&amp;lt;canvas id="color-block" height="150" width="150"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;canvas id="color-strip" height="150" width="30"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Now the fun begins...
  &lt;br&gt;
  Let's see how our JavaScript works:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;script type="text/javascript"&amp;gt;
// This is where the JavaScript code block begins
var colorBlock = document.getElementById('color-block');
var ctx1 = colorBlock.getContext('2d');
var width1 = colorBlock.width;
var height1 = colorBlock.height;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;



&lt;p&gt;These lines of code get the main canvas element with the identifier "&lt;em&gt;colour-block&lt;/em&gt;" from the HTML document. Then, the 2d context of the canvas is fetched using 
  &lt;code&gt;getContext('2d')
  &lt;/code&gt;. We also store the dimensions (width and height) of the canvas in the variables &lt;em&gt;width1&lt;/em&gt; and &lt;em&gt;height1&lt;/em&gt;. We continue:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
var colorStrip = document.getElementById('color-strip');
var ctx2 = colorStrip.getContext('2d');
var width2 = colorStrip.width;
var height2 = colorStrip.height;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;As you can see, the code is similar to the previous one, but in this case they obtain the canvas element of the colour strip with the identifier "&lt;em&gt;colour-strip&lt;/em&gt;". The 2d context of the canvas is obtained and the dimensions are stored in the variables &lt;em&gt;width2&lt;/em&gt; and &lt;em&gt;height2&lt;/em&gt;.
&lt;/p&gt;

&lt;p&gt;Now we have to get the HTML document elements with the identifiers "&lt;em&gt;colour-labe&lt;/em&gt;l", "&lt;em&gt;txtRgba&lt;/em&gt;" and "&lt;em&gt;txtHex&lt;/em&gt;" and we have to store them in corresponding variables. These elements are used to display and update the selected colour values.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
var colorLabel = document.getElementById('color-label');
var txtRgba = document.getElementById('txtRgba');
var txtHex = document.getElementById('txtHex');
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Let's add the variables needed to track the position of the mouse on the canvas to control whether it is dragging or not: x and y store the mouse coordinates, drag indicates whether the mouse is dragging and rgbaColor stores the initial value of the colour in RGBA format (red, green, blue and transparency).
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
var x = 0;
var y = 0;
var drag = false;
var rgbaColor = 'rgba(255,0,0,1)';
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;And now we define the colour gradients on the canvases. In the canvas &lt;em&gt;colourBlock&lt;/em&gt;, we draw a rectangle that covers the whole canvas and then call the &lt;em&gt;fill&lt;/em&gt; function
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
ctx1.rect(0, 0, width1, height1);
fillGradient();
ctx2.rect(0, 0, width2, height2);
var grd1 = ctx2.createLinearGradient(0, 0, 0, height1);
grd1.addColorStop(0, 'rgba(255, 0, 0, 1)');
grd1.addColorStop(0.17, 'rgba(255, 255, 0, 1)');
grd1.addColorStop(0.34, 'rgba(0, 255, 0, 1)');
grd1.addColorStop(0.51, 'rgba(0, 255, 255, 1)');
grd1.addColorStop(0.68, 'rgba(0, 0, 255, 1)');
grd1.addColorStop(0.85, 'rgba(255, 0, 255, 1)');
grd1.addColorStop(1, 'rgba(255, 0, 0, 1)');
ctx2.fillStyle = grd1;
ctx2.fill();
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;We add the function that is executed when you click on the colour strip canvas (&lt;em&gt;colourStrip&lt;/em&gt;) with the following characteristics: when you click, you have to get the coordinates (&lt;em&gt;offsetX and offsetY&lt;/em&gt;) of the point where you clicked. Then, the pixel colour corresponding to those coordinates is obtained using 
  &lt;code&gt;getImageData()
  &lt;/code&gt;. The result is stored in imageData, which is an object containing information about the RGBA components of the pixel. An rgbaColor string is constructed using these values and the 
  &lt;code&gt;fillGradient()
  &lt;/code&gt; function is called to update the colour in the main canvas.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
function click(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx2.getImageData(x, y, 1, 1).data;
rgbaColor = 'rgba(' + imageData[0] + ',' + imageData[1] + ',' + imageData[2] + ',1)';
fillGradient();
}
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;We create the function 
  &lt;code&gt;fillGradient()
  &lt;/code&gt; which draws the gradients on the main canvas (&lt;em&gt;colourBlock&lt;/em&gt;) to represent the selected colour. First, the fill colour is set to ctx1 with the value of rgbaColor and a rectangle is drawn covering the whole canvas. Then, two linear gradients, grdWhite and grdBlack, are created using the canvas context of the colour strip (&lt;em&gt;ctx2&lt;/em&gt;). These gradients are used to create a gradient effect on the main canvas, providing areas of black and white to adjust the brightness and contrast of the selected colour.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
function fillGradient() {
ctx1.fillStyle = rgbaColor;
ctx1.fillRect(0, 0, width1, height1);
var grdWhite = ctx2.createLinearGradient(0, 0, width1, 0);
grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
ctx1.fillStyle = grdWhite;
ctx1.fillRect(0, 0, width1, height1);
var grdBlack = ctx2.createLinearGradient(0, 0, 0, height1);
grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
ctx1.fillStyle = grdBlack;
ctx1.fillRect(0, 0, width1, height1);
}
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The following functions are used to control the user's interaction with the main canvas (&lt;strong&gt;colourBlock&lt;/strong&gt;). When the user presses the mouse button inside the canvas (&lt;strong&gt;mousedown&lt;/strong&gt;), drag is set to true to indicate dragging. The 
  &lt;code&gt;changeColor()
  &lt;/code&gt; function is called to update the selected colour.
&lt;/p&gt;

&lt;p&gt;During mousemove, if drag is true, 
  &lt;code&gt;changeColor() 
  &lt;/code&gt;is called to update the selected colour while dragging the mouse.
&lt;/p&gt;

&lt;p&gt;When the mouse button is released inside the canvas (&lt;strong&gt;mouseup&lt;/strong&gt;), drag is set to false to indicate that dragging is finished.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
function mousedown(e) {
drag = true;
changeColor(e);
}
function mousemove(e) {
if (drag) {
changeColor(e);
}
}
function mouseup(e) {
drag = false;
}
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Let's go ahead with the code for the 
  &lt;code&gt;changeColor()
  &lt;/code&gt; function used to update the selected colour when the user interacts with the main canvas. First, we get the coordinates of the point where the interaction occurred (&lt;strong&gt;offsetX and offsetY&lt;/strong&gt;). Then, the corresponding pixel colour is obtained using 
  &lt;code&gt;getImageData() 
  &lt;/code&gt;and the&lt;em&gt; rgbaColor&lt;/em&gt; variable is updated.
&lt;/p&gt;

&lt;p&gt;After that, the background colour of the colourLabel element is updated with the selected colour, the colour value is displayed in RGBA format in the txtRgba element and the colour is converted from RGBA to hexadecimal format using the 
  &lt;code&gt;rgbaToHex()
  &lt;/code&gt; function. The result is displayed in the txtHex element and is also printed to the console.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
function changeColor(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx1.getImageData(x, y, 1, 1).data;
rgbaColor = 'rgba(' + imageData[0] + ',' + imageData[1] + ',' + imageData[2] + ',1)';
colorLabel.style.backgroundColor = rgbaColor;
txtRgba.innerHTML = rgbaColor;
var hexColor = rgbaToHex(rgbaColor);
console.log(hexColor);
txtHex.innerHTML = hexColor;
}
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;These next lines of code assign the event handlers to the canvas elements and the colour strip element. When the colour strip is clicked, the 
  &lt;code&gt;click()
  &lt;/code&gt; function is executed. When the mouse is pressed, released or moved within the main canvas, the corresponding functions (
  &lt;code&gt;mousedown(), mouseup(), mousemove()
  &lt;/code&gt;) are executed to control the interaction and update the selected colour.
&lt;/p&gt;

&lt;pre&gt;
colorStrip.addEventListener("click", click, false);
colorBlock.addEventListener("mousedown", mousedown, false);
colorBlock.addEventListener("mouseup", mouseup, false);
colorBlock.addEventListener("mousemove", mousemove, false);
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The 
  &lt;code&gt;rgbaToHex() 
  &lt;/code&gt;function converts a colour in &lt;strong&gt;RGBA&lt;/strong&gt; format to hexadecimal format. First, the R, G, B and A component values of the RGBA colour are extracted using regular expressions. Then, the R, G and B values are converted to hexadecimal format using 
  &lt;code&gt;toString(16)
  &lt;/code&gt; and 
  &lt;code&gt;padStart(2, '0') 
  &lt;/code&gt;to make sure they have two digits. Finally, the hexadecimal values are combined and the colour is returned in hexadecimal format.
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
function rgbaToHex(rgbaColor) {
var values = rgbaColor.match(/d+/g);
var r = parseInt(values[0]);
var g = parseInt(values[1]);
var b = parseInt(values[2]);
var a = parseFloat(values[3]);
var hexR = r.toString(16).padStart(2, '0');
var hexG = g.toString(16).padStart(2, '0');
var hexB = b.toString(16).padStart(2, '0');
var hexColor = '#' + hexR + hexG + hexB;
return hexColor;
}
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Here is all the code:
&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;meta charset="utf-8" /&amp;gt;
&amp;lt;title&amp;gt;Colorpicker demo&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;style&amp;gt;
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
h2 {
background-color: #dbdbdb;
margin: 0;
margin-bottom: 15px;
padding: 10px;
font-family: 'Open Sans';
}
#color-input {
display: none;
}
#color-label {
margin-left: 15px;
position: absolute;
height: 30px;
width: 50px;
} 
#color-input:checked ~ #color-picker {
opacity: 1;
}
#color-picker {
position: absolute;
left: 70px; 
background-color: white;
height: 150px;
width: 185px;
border: solid 1px #ccc;
opacity: 0;
padding: 5px;
}
canvas:hover {
cursor: crosshair;
}
&amp;lt;/style&amp;gt;
&amp;lt;h2&amp;gt;Canvas Color Picker&amp;lt;/h2&amp;gt;
&amp;lt;div&amp;gt;&amp;lt;p&amp;gt;Color in RGBA is: &amp;lt;span id="txtRgba"&amp;gt;&amp;lt;/span&amp;gt; &amp;lt;/p&amp;gt;
&amp;lt;div&amp;gt;&amp;lt;p&amp;gt;Color in HEX is: &amp;lt;span id="txtHex"&amp;gt;&amp;lt;/span&amp;gt; &amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;label for="color-input" id="color-label" style="background-color: red"&amp;gt;&amp;lt;/label&amp;gt;
&amp;lt;input type="checkbox" id="color-input" checked&amp;gt;&amp;lt;/input&amp;gt;
&amp;lt;div id="color-picker"&amp;gt;
&amp;lt;canvas id="color-block" height="150" width="150"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;canvas id="color-strip" height="150" width="30"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;script type="text/javascript"&amp;gt;
var colorBlock = document.getElementById('color-block');
var ctx1 = colorBlock.getContext('2d');
var width1 = colorBlock.width;
var height1 = colorBlock.height;
var colorStrip = document.getElementById('color-strip');
var ctx2 = colorStrip.getContext('2d');
var width2 = colorStrip.width;
var height2 = colorStrip.height;
var colorLabel = document.getElementById('color-label');
var txtRgba = document.getElementById('txtRgba');
var txtHex = document.getElementById('txtHex');
var x = 0;
var y = 0;
var drag = false;
var rgbaColor = 'rgba(255,0,0,1)';
ctx1.rect(0, 0, width1, height1);
fillGradient();
ctx2.rect(0, 0, width2, height2);
var grd1 = ctx2.createLinearGradient(0, 0, 0, height1);
grd1.addColorStop(0, 'rgba(255, 0, 0, 1)');
grd1.addColorStop(0.17, 'rgba(255, 255, 0, 1)');
grd1.addColorStop(0.34, 'rgba(0, 255, 0, 1)');
grd1.addColorStop(0.51, 'rgba(0, 255, 255, 1)');
grd1.addColorStop(0.68, 'rgba(0, 0, 255, 1)');
grd1.addColorStop(0.85, 'rgba(255, 0, 255, 1)');
grd1.addColorStop(1, 'rgba(255, 0, 0, 1)');
ctx2.fillStyle = grd1;
ctx2.fill();
function click(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx2.getImageData(x, y, 1, 1).data;
rgbaColor = 'rgba(' + imageData[0] + ',' + imageData[1] + ',' + imageData[2] + ',1)';
fillGradient();
}
function fillGradient() {
ctx1.fillStyle = rgbaColor;
ctx1.fillRect(0, 0, width1, height1);
var grdWhite = ctx2.createLinearGradient(0, 0, width1, 0);
grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
ctx1.fillStyle = grdWhite;
ctx1.fillRect(0, 0, width1, height1);
var grdBlack = ctx2.createLinearGradient(0, 0, 0, height1);
grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
ctx1.fillStyle = grdBlack;
ctx1.fillRect(0, 0, width1, height1);
}
function mousedown(e) {
drag = true;
changeColor(e);
}
function mousemove(e) {
if (drag) {
changeColor(e);
}
}
function mouseup(e) {
drag = false;
}
function changeColor(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx1.getImageData(x, y, 1, 1).data;
rgbaColor = 'rgba(' + imageData[0] + ',' + imageData[1] + ',' + imageData[2] + ',1)';
colorLabel.style.backgroundColor = rgbaColor;
txtRgba.innerHTML = rgbaColor;
var hexColor = rgbaToHex(rgbaColor);
console.log(hexColor);
txtHex.innerHTML = hexColor;
}
colorStrip.addEventListener("click", click, false);
colorBlock.addEventListener("mousedown", mousedown, false);
colorBlock.addEventListener("mouseup", mouseup, false);
colorBlock.addEventListener("mousemove", mousemove, false);
function rgbaToHex(rgbaColor) {
var values = rgbaColor.match(/d+/g);
var r = parseInt(values[0]);
var g = parseInt(values[1]);
var b = parseInt(values[2]);
var a = parseFloat(values[3]);
var hexR = r.toString(16).padStart(2, '0');
var hexG = g.toString(16).padStart(2, '0');
var hexB = b.toString(16).padStart(2, '0');
var hexColor = '#' + hexR + hexG + hexB;
return hexColor;
}
&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;I hope that this tutorial has demonstrated the great potential that exists in developing applications using Canvas. There are much more advanced applications, and even games are being developed using this technology. It is therefore a field worth exploring, as it offers the possibility to create amazing and surprising things.
&lt;/p&gt;

</description>
      <category>html</category>
      <category>css</category>
      <category>javascript</category>
      <category>development</category>
    </item>
    <item>
      <title>How to connect to MySQL with Node.js</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Thu, 04 Nov 2021 17:51:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/how-to-connect-to-mysql-with-nodejs-26fo</link>
      <guid>https://dev.to/salvietta150x40/how-to-connect-to-mysql-with-nodejs-26fo</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GIsM0YJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2220/960-400/connect-mysql-to-node-js-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GIsM0YJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2220/960-400/connect-mysql-to-node-js-impjpg.webp" alt="How to connect to MySQL with Node.js" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment.&lt;br&gt;
Before we start, it is important to note that you must have Node.js installed on your system. Likewise, you must create a MySQL database.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h2&gt;Create a MySQL database&lt;/h2&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
If you haven't already done so, you can create the database in any way you like. You can create it using applications such as phpMyAdmin or manually using the MySQL command line. To create it via the command line, follow these steps:&lt;br&gt;
Connect to MySQL from the command line and enter the password when prompted:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;mysql -u USER -p&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
Create a sample table, which in this case we will call employees:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;CREATE DATABASE employees;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
Select the database you have just created:&lt;/p&gt;

&lt;pre&gt;USE employees;&lt;/pre&gt;

&lt;p&gt;Create a table in the database:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;CREATE TABLE IF NOT EXISTS employees (    
id int(11) NOT NULL AUTO_INCREMENT,    
name varchar(50),    
PRIMARY KEY (id)  
);&lt;/pre&gt;
&lt;br&gt;
Insert some example data in the table:
&lt;br&gt;
&lt;pre&gt;INSERT INTO employees (nombre) VALUES ("Silvia");  
INSERT INTO employees (nombre) VALUES ("Luigi");  
INSERT INTO employees (nombre) VALUES ("Alejandro");
&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
 &lt;br&gt;
You can now run queries on the table.&lt;br&gt;&lt;/p&gt;

&lt;h3&gt;Install node-mysql&lt;/h3&gt;

&lt;p&gt;You will need to have the node-mysql package installed, so if you don't have it installed, you will need to install it. To do this you must use the npm package manager:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;npm install mysql&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
After installing node-mysql you will be able to connect to the database via Node.js.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h3&gt;Establish the MySQL connection&lt;/h3&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
Create a Node.js script. &lt;br&gt;
The first thing we do in this example is create a connection object to the MySQL database. &lt;br&gt;
We use the table employees as an example, but replace it with the name of the database you want to use. Similarly, replace USER and PASS with the MySQL user data.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;var mysql = require('mysql');  
var conexion= mysql.createConnection({      
   host : 'localhost',      
   database : 'employees',      
   user : 'USER',      
   password : 'PASS',  
});    
conexion.connect(function(err) {     
   if (err) {          
       console.error('Error de conexion: ' + err.stack);          
       return;      
   }      
   console.log('Connected to the identifier ' + conexion.threadId); 
});&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
Once the connection is established, you will be able to execute queries using the query method:&lt;br&gt;
 &lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;conexion.query('SELECT * FROM empleados', function (error, results, fields) {
      if (error)          
          throw error;        
      results.forEach(result =&amp;gt; {          
      console.log(result);      
      });  
});&lt;/pre&gt;



&lt;p&gt;Finally, terminate the connection:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;connection.end();&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
And that's it. If you want more information about node-mysql, we recommend you to consult &lt;a href="https://www.npmjs.com/package/mysql" rel="nofollow noreferrer noopener"&gt;this guide&lt;/a&gt;.&lt;br&gt;
 &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
    </item>
    <item>
      <title>JavaScript Programming Styles: Best Practices</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Thu, 28 Oct 2021 10:40:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/javascript-programming-styles-best-practices-acg</link>
      <guid>https://dev.to/salvietta150x40/javascript-programming-styles-best-practices-acg</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5_Wa1MyM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2219/960-400/javascript-best-methods-imppng.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5_Wa1MyM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2219/960-400/javascript-best-methods-imppng.webp" alt="JavaScript Programming Styles: Best Practices" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When programming with JavaScript there are certain conventions that you should&lt;br&gt;
  apply, especially when working in a team environment. In fact, it is common to&lt;br&gt;
  have meetings to discuss standards to follow. The reason is that code is much&lt;br&gt;
  more readable when certain standards are followed. We have already seen in&lt;br&gt;
  another article some of the worst JavaScript practices, explaining certain&lt;br&gt;
  things to avoid. But when we talk about good practices we are not only&lt;br&gt;
  referring to those that have a better performance, but also to the way you&lt;br&gt;
  program. In addition to making sure that the code is syntactically correct,&lt;br&gt;
  you should also be concerned about styles; that is, things like where you&lt;br&gt;
  place the opening and closing braces or the spaces you use as indentation or&lt;br&gt;
  indentation in the code.&lt;/p&gt;

&lt;h2&gt;What are programming styles&lt;/h2&gt;


&lt;p&gt; Programming styles are nothing more than an agreement you make with your team&lt;br&gt;
  and yourself about the styles and standards you will follow in a project. The&lt;br&gt;
  goal of following a style is to achieve a consistent result, with code that is&lt;br&gt;
  easy to understand and maintain. Even if you are working alone on a personal&lt;br&gt;
  project you should follow certain standards. You may not see why during its&lt;br&gt;
  initial release, but you will when you modify the code in a few months or when&lt;br&gt;
  another programmer starts working on the project as well. &lt;/p&gt;

&lt;h3&gt;The importance of styles&lt;/h3&gt;

&lt;p&gt;Programming is something similar to craftsmanship, where factors such as&lt;br&gt;
  creativity, perseverance and expertise come into play. For example, you can&lt;br&gt;
  paint a wall and leave it smooth, with everything perfectly clean around you,&lt;br&gt;
  or you can paint the wall with irregularities or hand marks, fill the floor&lt;br&gt;
  with paint, and leave it all over. The same thing happens with programming,&lt;br&gt;
  becoming even more important, because when many programmers modify the same&lt;br&gt;
  code over and over again, if each one applies his own rules, the result may&lt;br&gt;
  look more like the second case.&lt;/p&gt;

&lt;p&gt;It is very common that some inexperienced programmers do not care about this,&lt;br&gt;
  since they have not yet been able to understand its importance. I was also one&lt;br&gt;
  of them and absolutely all programmers have been. Besides, it is in this kind&lt;br&gt;
  of little things where the team leaders will perceive your experience. &lt;/p&gt;

&lt;h3&gt;Sets of style standards&lt;/h3&gt;

&lt;p&gt;There are different sets of standards that you could follow. Each company has&lt;br&gt;
  its own, and that is what styles are all about, following the same ones within&lt;br&gt;
  the framework of a company or project, without there being a set that is&lt;br&gt;
  better or worse. Here are the two most famous sets of styles: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt; On the one hand you have the &lt;a href="https://google.github.io/styleguide/jsguide.html" title="Google JavaScript styles"&gt;Google JavaScript styles.&lt;/a&gt; &lt;/li&gt;
  &lt;li&gt; On the other hand you have the &lt;a href="https://github.com/airbnb/javascript" title="AirBnb JavaScript styles"&gt;AirBnb JavaScript styles. &lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In my case, the styles I follow are very similar to AirBnb's, as they are the&lt;br&gt;
  ones I've gotten used to in the companies I've worked for. If you prefer&lt;br&gt;
  another set use it, but don't change it until you finish the project. &lt;br&gt;
 You also have the option of using tools like ESLint or Prettier, which somehow&lt;br&gt;
  force you to use certain rules. &lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;Method, function and variable notation&lt;/h2&gt;
&lt;br&gt;&lt;br&gt;
 There are different types of notations that you could follow when defining the&lt;br&gt;
  names of functions and variables. The most famous are the following: 

&lt;p&gt;&lt;strong&gt;Camel Case&lt;/strong&gt;: This style combines the words of the names you&lt;br&gt;
  define, setting the first letter of each word to be capitalized except for the&lt;br&gt;
  first word, with the rest of the letters being lowercase. If you wanted to&lt;br&gt;
  define an account management function using Camel Case, its name would be&lt;br&gt;
  accountManagement. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pascal Case&lt;/strong&gt;: This style combines the words of the names you&lt;br&gt;
  define, establishing that the first letter of each word is in upper case,&lt;br&gt;
  including the first word, the rest of the letters being in lower case. If you&lt;br&gt;
  wanted to define an account management function using Pascal Case its name&lt;br&gt;
  would be GestionDeCuentas. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Snake Case&lt;/strong&gt;: This style combines the words of the names you&lt;br&gt;
  define, setting all letters to lower case and all words to be separated by an&lt;br&gt;
  underscore. If you wanted to define an account management function using Snake&lt;br&gt;
  Case its name would be account_management. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kebab Case&lt;/strong&gt;: This style combines the words of the names you&lt;br&gt;
  define, setting all letters to lower case and all words to be separated by a&lt;br&gt;
  hyphen. If you wanted to define an account management function using Snake&lt;br&gt;
  Case its name would be account-management. &lt;/p&gt;

&lt;p&gt;There is no better method, although the truth is that in JavaScript the Kebab&lt;br&gt;
  Case would be practically discarded. The usual is to use Pascal Case for class&lt;br&gt;
  names and Pascal Case for almost everything else, although there are many&lt;br&gt;
  developers who prefer to define variable names with Snake Case. If you want&lt;br&gt;
  more examples, see the guide with the different types of notation for names. &lt;/p&gt;

&lt;h2&gt;Rules to use: Yours&lt;/h2&gt;

&lt;p&gt;That's the way it is and will be as long as you are consistent. Here are mine,&lt;br&gt;
  which although they are very similar to AirBnb's, they don't coincide 100%: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Semicolons: &lt;/strong&gt; Many developers choose not to put them at the&lt;br&gt;
  end of each line, although in my case I use them religiously at the end of&lt;br&gt;
  each line to avoid possible problems that could occur in some cases. &lt;br&gt;
¡&lt;br&gt;
 &lt;strong&gt;Spaces:&lt;/strong&gt; I always prefer to use more spaces than less. I&lt;br&gt;
  usually use them whenever I close a parenthesis unless it is the end of a line&lt;br&gt;
  and also before and after the symbols of arithmetic operations such as +, -, /&lt;br&gt;
  or *, checks or conditions. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Blank lines: &lt;/strong&gt;I use a line break to separate blocks of code&lt;br&gt;
  that deal with different logical operations. This way I think it is easier to&lt;br&gt;
  read the code. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Indenting: &lt;/strong&gt; I use 4 spaces instead of pressing the tab key. It&lt;br&gt;
  is also common to use two spaces. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Line length: &lt;/strong&gt; The length of my lines does not exceed 120&lt;br&gt;
  characters. Many developers opt for 80 characters, but I find it too short. I&lt;br&gt;
  have a bad habit of using lines that are too long. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Comments:&lt;/strong&gt; I usually use comment blocks to document the code, and in case of commenting something, I write the comment in the line above the one I want to comment instead of writing it at the end of the line. In the same way, I only write the comments that are necessary. That is, I don't use comments when the code blocks that follow the JSDoc standard are sufficient or when the variable names make it very easy to understand what I want to do.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variable declarations: &lt;/strong&gt; I never declare variables with var. I use const when a value or reference is not going to change, and let when I want to declare a variable. I always declare constants first and then variables, being both at the beginning of the document in the case of global variables, or at the beginning of functions, in the case of local variables. This way we avoid the unwanted effects of JavaScript hoisting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Function structure: &lt;/strong&gt;I use arrow functions whenever possible because of the treatment of this. Sometimes, as in the case of constructors, it is not. Whenever I can, I define functions like this:&lt;/p&gt;

&lt;pre&gt;const miFuncion = (a, b) =&amp;gt; a * b;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Variable names&lt;/strong&gt;: I always use Camel Case, although until not too long ago I used Snake Case. This is an example of &lt;code&gt;camelCase&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class names: &lt;/strong&gt;In this case I use Pascal Case, both in the class name and in the name of the file that includes it. This is an example of &lt;code&gt;PascalCase&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single or double quotes:&lt;/strong&gt; Whenever possible I use single quotes instead of double quotes. I usually reserve double quotes for HTML attribute tags, so that if I have to insert JavaScript inside them, I can do it with double quotes. I also apply this criterion with other programming languages such as PHP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Template Literals:&lt;/strong&gt; These are expressions that use inverted quotation marks &lt;code&gt;to define strings. Whenever I have to insert variables in text strings, I use these quotes, inserting the variable in the middle. In the following tutorial you can find more information about template literals. Example:&lt;/code&gt;&lt;em&gt;Here I am inserting a ${variable}&lt;/em&gt;` .&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Function and method names:&lt;/strong&gt; As in the case of variables, I use Camel Case for both functions and methods of classes. Example: CamelCase.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If statements: &lt;/strong&gt;In this case I usually use two varieties, since I can place the statements in one or several lines depending on how long they are:&lt;/p&gt;

&lt;pre&gt;
// If normal 
if (condition) {    
  // code
}
    
// If con un else 
if (condition) {    
  // código 
} else {    
  // code 
} 
   
// If with several else 
if (condition) {    
   // code 
} else if (condition) 
{    
  // code
} else {    
// code }

&lt;/pre&gt;

&lt;p&gt;In the case of very short statements, I use a single line. This is something quite criticized by some developers but I find it very readable as long as the statements are very short, like when you make assignments to a variable. In any other case I use several lines:&lt;/p&gt;

&lt;pre&gt;

// If normalif (statement) variable = true; 
   
// If with one else 
if (statement) variable = true;  
else variable = false;

&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Switch statements:&lt;/strong&gt; In this case I always define a default condition and also use several lines:&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;pre&gt;
switch (expression) {    
case expression:      
// code   
default:      
// code 
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;For loops:&lt;/strong&gt; I always use several lines. In this case I always initialize the element defining the loop iterations in its own definition. I consider this better than inserting it in the condition. I separate the different elements of the loop definition by a&lt;code&gt; ;&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;
for (initialization; condition; update) {    
// code
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;While loops&lt;/strong&gt;: I always use several lines:&lt;/p&gt;

&lt;pre&gt;
while (condition) {
  // code
  }
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Do while loops: &lt;/strong&gt;I don't usually use this loop too much. In several lines:&lt;/p&gt;

&lt;pre&gt;
do {
  // code
  } while (condicion);```
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Try/catch/finally statements: &lt;/strong&gt;This is how I define them:&lt;/p&gt;

&lt;pre&gt;
// try catch
  try {
  // code
  } catch (error) {
  // code
  }

// try catch finally
  try {
  // code
  } catch (error) {
  // code
  } finally {
  // code
  }
&lt;/pre&gt;

&lt;p&gt;Whatever style you choose, remember that the important thing is to be consistent and maintain it throughout your project. &lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Validating Html Forms Using Bulma and Vanilla Javascript</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Tue, 19 Jan 2021 11:23:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/validating-html-forms-using-bulma-and-vanilla-javascript-2b37</link>
      <guid>https://dev.to/salvietta150x40/validating-html-forms-using-bulma-and-vanilla-javascript-2b37</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w73az4Cr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/960-400/logo_complete-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w73az4Cr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/960-400/logo_complete-impjpg.webp" alt="Validating Html Forms Using Bulma and Vanilla Javascript" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Today we are going to write about contact forms and how to validate them using JavaScript.&lt;/p&gt;

&lt;p&gt;The contact form seems to be one of the top features of every basic home page. It is a great way to encourage your visitors to make contact with you, by adding a form which is nice to look at, simple to use and easy to submit. A good web form should to some extent follow the well-known, popular usual style so that your users already have knowledge on how to fill out its input fields and never have to think twice about what kind of data is required and where. We mean the user should never wonder which field is required and which is optional and how to fill them out correctly and how to submit the form successfully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Form creation rules
&lt;/h2&gt;

&lt;p&gt;Before starting to create the form itself, it is a good practice to take the time and think about what kind of information you are going to ask your user. And also, which fields are going to be required and which can be submitted empty? Are there any restrictions when it comes to the format of the data that he/she enters?&lt;br&gt;
A HTML form’s complexity may range from a plain and simple contact form where we only ask the user to fill out his name, email, phone and a message or it may be a more elaborate form as is the case with new user registration, for example.&lt;br&gt;
We want to make our form better by giving the user interactive real time feedback about if he is filling out the input fields correctly, and let him know if there is a field missing or if it is incorrect&lt;/p&gt;

&lt;h2&gt;
  
  
  Data validation
&lt;/h2&gt;

&lt;p&gt;Another aspect is the question of data validation. Every time you need to work with input generated by some user, you MUST validate that the data he is submitting is in accordance with your expectations. This means there are conditions, like for example an email input field should definitely contain the @ sign and then a . followed by the domain name. Or a phone number should consist of the + sign and numbers exclusively. Also, you might wish to check that the length of the word that the user has entered is greater than a certain number of characters, so for example you might not want people submitting words shorter than let’s say 3 characters as the message’s body.&lt;/p&gt;

&lt;p&gt;Another interesting effect of validating your data in the front-end part of your website’s code is the added advantage of protection against cyber attacks. Always think that if there are input fields in your page, a malicious agent such as a bot might come and attack your site’s code, integrity or availability and thus try and hack your web. Best way of preventing things like this from happening is by double hacker-proofing your code by using front end validation mechanisms like JavaScript validation as well as back end, server-side data validation. These two should make a protection-duo to make it as much difficult as possible for attackers to infiltrate your site.&lt;/p&gt;

&lt;h2&gt;
  
  
  Contact form accessibility
&lt;/h2&gt;

&lt;p&gt;When designing a contact form, it is of great usefulness to make use of special HTML attributes to make your form more accessible. By this we mean to assign correctly the order of the input fields so that the form can be easily navigated by using keyboard only. You can also improve the ease of use by using the label element, so that input fields are focused upon clicking on the title assigned in the label.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bulma integration
&lt;/h2&gt;

&lt;p&gt;How can we make use of BULMA in the case of designing html contact forms?&lt;br&gt;
Bulma is a framework, a library similar to Bootstrap which if you learn to use can simplify the css part of your job when designing a web page. We will especially make use of the Bulma’s form section. It’s based on flexbox so we make use of it to position our elements on the screen - specifically our icons. In our little example, the classes will be the modifiers that will tell the icons where to shift or how to look like and that’ll make our life a bit easier.&lt;/p&gt;

&lt;p&gt;Has-icons-right, has-icons-left, is-danger, is-small, is-right, etc.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hNrJ48xF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/bulma_form.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hNrJ48xF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/bulma_form.jpg" alt="Bulma form" width="800" height="546"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We aim to create a simple contact form, in which will be using the following HTML mark-up:&lt;/p&gt;

&lt;pre&gt;&amp;lt;section class="section" id="contact"&amp;gt;
 &amp;lt;div class="container is-max-desktop"&amp;gt;
 &amp;lt;h2 class="title"&amp;gt;CONTACT&amp;lt;/h2&amp;gt;
 &amp;lt;h3&amp;gt;If you wish to get in touch with Majka, send her a message&amp;lt;/h3&amp;gt;
 &amp;lt;form accept-charset="utf-8" action="sendmail.php" method="post" enctype="multipart/form-data"&amp;gt;
 &amp;lt;/form&amp;gt;
 &amp;lt;/div&amp;gt;
&amp;lt;/section&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Now this alone will not be sufficient, we also want to have input fields and some buttons, so we add inside element &lt;strong&gt;&amp;lt;form&amp;gt;&lt;/strong&gt; the following - name, email, phone number and message fields and a submit button.&lt;/p&gt;

&lt;pre&gt;&amp;lt;!--Name field--&amp;gt;
&amp;lt;div class="field"&amp;gt;
&amp;lt;label class="label" for="name"&amp;gt;Your Name&amp;lt;/label&amp;gt;
&amp;lt;div class="control has-icons-right"&amp;gt;
 &amp;lt;input class="input needs-validation inputNameField" type="text" name="name" placeholder="name maximum 20 characters" value="" id='inputName' /&amp;gt;
 &amp;lt;span class="icon is-small is-right"&amp;gt;
 &amp;lt;i id='nameCheckIcon' class="fas fa-exclamation-triangle"&amp;gt;&amp;lt;/i&amp;gt;
 &amp;lt;/span&amp;gt;
 &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!--Email field--&amp;gt;
&amp;lt;div class="field"&amp;gt;
 &amp;lt;label class="label" for="email"&amp;gt;Email&amp;lt;/label&amp;gt;
 &amp;lt;div class="control has-icons-left has-icons-right"&amp;gt;
 &amp;lt;input class="input needs-validation inputEmailField" type="email" name="email" placeholder="your@email" value="" id='inputEmailField' /&amp;gt;
 &amp;lt;span class="icon is-small is-left"&amp;gt;
 &amp;lt;i class="fas fa-envelope"&amp;gt;&amp;lt;/i&amp;gt;
 &amp;lt;/span&amp;gt;
 &amp;lt;span class="icon is-small is-right"&amp;gt;
 &amp;lt;i id='emailCheckIcon' class="fas fa-exclamation-triangle"&amp;gt;&amp;lt;/i&amp;gt;
 &amp;lt;/span&amp;gt;
 &amp;lt;/div&amp;gt;
 &amp;lt;p id="emailActionHint" class="help is-danger nezobrazovat"&amp;gt;Please enter a valid email so Majka can reach you&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!--Phone number field--&amp;gt;
&amp;lt;div class="field"&amp;gt;
 &amp;lt;label class="label" for="number"&amp;gt;Phone Number&amp;lt;/label&amp;gt;
 &amp;lt;div class="control has-icons-left has-icons-right"&amp;gt;
 &amp;lt;input class="input is-warning" type="text" name="number" placeholder="" value="" /&amp;gt;
 &amp;lt;span class="icon is-small is-left"&amp;gt;
 &amp;lt;i class="fas fa-phone"&amp;gt;&amp;lt;/i&amp;gt;
 &amp;lt;/span&amp;gt;
 &amp;lt;span class="icon is-small is-right"&amp;gt;
 &amp;lt;i class="fas fa-exclamation-triangle"&amp;gt;&amp;lt;/i&amp;gt;
 &amp;lt;/span&amp;gt;
 &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!--Message field--&amp;gt;
&amp;lt;div class="field"&amp;gt;
 &amp;lt;label class="label"&amp;gt;Your Message&amp;lt;/label&amp;gt;
 &amp;lt;div class="control"&amp;gt;
 &amp;lt;textarea class="textarea" name="message" placeholder=""&amp;gt;&amp;lt;/textarea&amp;gt;
 &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!--Submit checkbox--&amp;gt;
&amp;lt;div class="field"&amp;gt;
 &amp;lt;div class="control"&amp;gt;
 &amp;lt;label class="checkbox"&amp;gt;
 &amp;lt;input type="checkbox" /&amp;gt;
 I agree to the &amp;lt;a href="#"&amp;gt;terms and conditions&amp;lt;/a&amp;gt;
 &amp;lt;/label&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!--Submit button--&amp;gt;
&amp;lt;div class="field is-grouped"&amp;gt;
 &amp;lt;div class="control"&amp;gt;
 &amp;lt;button class="button is-light" id="submitButton" disabled="true"&amp;gt;Submit&amp;lt;/button&amp;gt;
 &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt;As you can see, we have four different input fields:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--V0DuEMbc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/contact_form.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--V0DuEMbc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/contact_form.jpg" alt="Bulma form" width="800" height="464"&gt;&lt;/a&gt; &lt;br&gt;
This line we add to the end of the body, but before closing element &amp;lt;/body&amp;gt;. This will do that the javascript will be loaded after the HTML code is executed, or we can add “async defer” property to the &amp;lt;script&amp;gt;, which will do the trick and then your script could be placed anywhere on the page and still the script will run at the end like we want.&lt;/p&gt;

&lt;pre&gt;&amp;lt;script src="js/main.js?v6" async defer&amp;gt;&amp;lt;/script&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Note: If you're asking what is “?v6” behind the .js file, that's the version of the JS code, when you need your code editor would read the latest non cached code, you just raise the number of the version and it will load your latest changes to the code.&lt;/p&gt;

&lt;p&gt;And now let’s set up the most interesting part – the JavaScript code to check the fields’ content and validate their state:&lt;br&gt;
  First we can define constants which will represent our elements we want to work with.&lt;/p&gt;

&lt;pre&gt;const ourParallax = document.getElementById('parallax')
const parallaxInstance = new Parallax(ourParallax)
const submit = document.getElementById('submitButton')
const inputName = document.getElementById('inputName')
const inputEmail = document.getElementById('inputEmailField')
const iconName = document.getElementById('nameCheckIcon')
const iconEmail = document.getElementById('emailCheckIcon')
const MAXCHARNAMEFIELD = 20
const MINCHARNAMEFIELD = 3
&lt;/pre&gt;

&lt;p&gt;But let's continue. We now set up Event Listeners which will be waiting for some specific action to be happening.&lt;/p&gt;

&lt;pre&gt;// EVENT LISTENERS
document.addEventListener('change', event =&amp;gt; { 

 if (event.target.matches('.inputNameField')) {
 validateName()
 } else if (event.target.matches('.inputEmailField')) {
 validateEmail(event.target.value)
 } else {
 //nothing
 }
}, false)

&lt;/pre&gt;

&lt;p&gt;To describe it further - on the whole page we have one listener and when something will change - like its defined inside the parentheses is set on what event -&amp;gt; on ‘change’, it will execute the arrow function. Inside the arrow function we have an IF statement to resolve if the event happened on some of the next elements we have.&lt;br&gt;
  For example, if there is some ‘change’ event - we write something in the HTML element input field which has CSS class .inputNameField, IF statement will be true and the next code will be executed. And the code which we have on execution is function validateName() - it's time to describe its code now :&lt;/p&gt;

&lt;h3&gt;
  
  
  Name Validation
&lt;/h3&gt;

&lt;pre&gt;function validateName() {
 var regexString = /w?s?w/g; //words separated by space

 const iconName = document.getElementById('nameCheckIcon')
 const conditions =
 (inputName.value.length &amp;gt; MINCHARNAMEFIELD) &amp;amp;&amp;amp;
 (inputName.value.length &amp;lt; MAXCHARNAMEFIELD) &amp;amp;&amp;amp;
 (inputName.value != null) &amp;amp;&amp;amp;
 (regexString.test(inputName.value)) //test for regex string
 console.log(regexString.test(inputName.value))

 if (conditions) {
 // input box color
 inputName.classList.remove('is-danger')
 inputName.classList.add('is-success')
 // icon type
 iconName.classList.remove('fa-exclamation-triangle')
 iconName.classList.add('fa-check')
 // console.log("icon :" + icon.classList.value)

 //now we call submit button test
 nameValidated = true
 submitCheck()
 } else {
 // input box color
 inputName.classList.remove('is-sucess')
 inputName.classList.add('is-danger')
 // icon type
 iconName.classList.remove('fa-check')
 iconName.classList.add('fa-exclamation-triangle')

 nameValidated = false
 }
}
&lt;/pre&gt;

&lt;p&gt;We define variable with regular expression first.&lt;br&gt;
Also we add two constants to the definition of the variables at the start, which will represent the minimum and maximum characters we want our input field to have. This is the right way to do it, this way you won't have any undescribed constants in your conditionals, so called ‘magic numbers’.&lt;/p&gt;

&lt;pre&gt;const MAXCHARNAMEFIELD = 20
const MINCHARNAMEFIELD = 3
&lt;/pre&gt;

&lt;p&gt;We make new variable to the icon we would be working with, so far the icon which belongs to the Name input field has Bulma class ‘fa-exclamation-triangle’, and we will change it when the input field is correctly filled.&lt;br&gt;
  Next we have series of conditions we want to be checked - input will be checked against all of them and when all are boolean true, for the element set to the variable inputName = document.getElementById('inputName') -declared earlier, we remove the class ‘is-danger’ and we add class ‘is-success’. This will change the color of the field to green. Similarly, to the icon we remove ‘fa-exclamation-triangle’ and add ‘fa-check’, which will make that check icon is displayed.&lt;br&gt;
  We declare new variables with default state = false ,added to the start of the file where we have other variables.&lt;/p&gt;

&lt;pre&gt;var nameValidated = false
var emailValidated = false
&lt;/pre&gt;

&lt;p&gt;Also we want to set a new variable when the input field for the name is correctly filled to ‘true’. This will be useful when we come to the submit button later. The last thing is to call the function submitCheck() every time the change happens to the form. It will execute that function but so far we can ignore it until later. Allright, we should have this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o8l3Innt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/input_name.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o8l3Innt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/input_name.jpg" alt="Bulma form" width="416" height="130"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Email Validation
&lt;/h2&gt;

&lt;p&gt;Next we have validateEmail(value) function, which will be called when some ‘change’ event happens on this HTML element, remember?&lt;/p&gt;

&lt;pre&gt;validateEmail(event.target.value)
&lt;/pre&gt;

&lt;pre&gt;function validateEmail(value) {
 const iconEmail = document.getElementById('emailCheckIcon')
 const emailParagraph = document.getElementById('emailActionHint')

 if (validateRegexString(value)) {
 // input box color
 inputEmail.classList.remove('is-danger')
 inputEmail.classList.add('is-success')
 // icon type
 iconEmail.classList.remove('fa-exclamation-triangle')
 iconEmail.classList.add('fa-check')
 emailParagraph.style = 'display:none'

 emailValidated = true
 submitCheck()
 } else {
 // input box color
 inputEmail.classList.remove('is-sucess')
 inputEmail.classList.add('is-danger')
 // icon type
 iconEmail.classList.remove('fa-check')
 iconEmail.classList.add('fa-exclamation-triangle')
 emailParagraph.style = 'display:block'

 emailValidated = false
 }
}
&lt;/pre&gt;

&lt;p&gt;Let's describe the function.&lt;br&gt;
  We declare as variable two elements, icon and paragraph with text we want to show, this paragraph is momentarily hidden (CSS style display:none) so by the load of the page by default there is no text shown.&lt;br&gt;
  Next we have a condition where we have called yet another function added to the code - validateRegexString(value), which returns true when the string entered into the input is validated by this function.&lt;/p&gt;

&lt;pre&gt;function validateRegexString(email) {
 const regexString = /^(([^&amp;lt;&amp;gt;()[].,;:s@"]+(.[^&amp;lt;&amp;gt;()[].,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/
 return regexString.test(String(email).toLowerCase()) // true|false
}
&lt;/pre&gt;

&lt;p&gt;Well if the condition is fulfilled and we for example have a valid email, valid in the sense of the characters entered are looking as an email address, the code will remove red color from the input field, add green color (Bulma classes), from icon removes exclamation triangle and adds check pictogram. Also it keeps from displaying any warning text we have prepared in the element &amp;lt;p&amp;gt; with id = ‘emailParagraph’.
  
  
  ![Bulma form](https://www.ma-no.org/cache/galleries/contents-2114/input_email.jpg)&lt;/p&gt;

&lt;p&gt;At the end like in the previous validateName() function we have added emailValidated = true and call to the submitCheck() function.
  
  
  ## Submit Button
  
  The next and the last element we will be showing is how to make the submit button disabled and only be enabled after the data we want are filled in. So for example we can make the button unclickable unless there is a filled input field name and email, but not the phone and text message, which could be empty. Let's get to the code.
  
  
  ![Bulma form](https://www.ma-no.org/cache/galleries/contents-2114/submit_disabled.jpg)&lt;/p&gt;

&lt;p&gt;Remember that we have two variables defined by default, nameValidated and emailValidated, and we can use them in the condition to the function submitCheck() - it will be called every time when the input field for name and email is successfully validated. When both are validated and in our variables value is now set to true, the button would be unblocked by removing the attribute ‘disabled’ which has by default.&lt;/p&gt;

&lt;pre&gt;function submitCheck() {
 const emailParagraph = document.getElementById('emailActionHint')
 console.log(nameValidated, emailValidated)
 if (nameValidated &amp;amp;&amp;amp; emailValidated) {

 submit.disabled = false; //button is no longer no-clickable
 submit.removeAttribute("disabled"); //detto
 } else {
 emailParagraph.style = 'display:block' //email warning shows up
 }
}
&lt;/pre&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1NfGpzya--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/submit_enabled.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1NfGpzya--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2114/submit_enabled.jpg" alt="Bulma form" width="800" height="475"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;And that’s it! We successfully designed a simple contact form which can be (and in some form should be) used on any web page. The HTML markup makes correct use of accessibility enhancing attributes. Thanks to the Bulma CSS framework, our form has a neat and elegant look, with icons and colors providing the user with feedback on if the form is filled out correctly. The validation part is possible thanks to our simple vanilla JS script, which uses regular expressions and simple mathematical functions to confirm the data entered is valid.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>bulma</category>
    </item>
    <item>
      <title>What Is Django and What Is It Used For</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Sat, 26 Dec 2020 11:23:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/what-is-django-and-what-is-it-used-for-2nk0</link>
      <guid>https://dev.to/salvietta150x40/what-is-django-and-what-is-it-used-for-2nk0</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ERyk8QR0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2105/960-400/django-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ERyk8QR0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2105/960-400/django-impjpg.webp" alt="What Is Django and What Is It Used For" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  An high-level Python Web framework that encourages rapid development and clean design
&lt;/h2&gt;

&lt;p&gt;When we talk about Django, we refer to that framework that is used for any totally free and open source web application which is written in Python. Basically, it's a group of elements that will help you create web pages much more easily and quickly.&lt;/p&gt;

&lt;p&gt;At the moment you are going to make a web page, you usually require several similar elements: a way to control all authentication by users such as their (registration, login, completion), the panel to manage the web page, the various forms, the ability to upload a document or file, etc.&lt;/p&gt;

&lt;p&gt;There are several guys who realized that every web developer faces similar issues when making a site. That's why they have joined forces and developed frameworks (Django being part of one of these) which will provide you with the elements to build your website.&lt;/p&gt;

&lt;p&gt;These framworks are there to speed up the web creation process and not to have to reinvent the wheel in general. That way, you will get support by relieving the weight when creating the web.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why do I need a framework?
&lt;/h3&gt;

&lt;p&gt;If you want to understand what Django is all about, you need to look a little closer at each server. The main thing is that a server needs to know what you want to make a website useful.&lt;/p&gt;

&lt;p&gt;Let's imagine we have a mailbox where this would be the port. This is constantly monitored by letters that would come as requests. This is done by a web server. The moment you want to send something, you must load it with the appropriate content. Django is in charge of helping you create the content.&lt;/p&gt;

&lt;p&gt;What's Django?&lt;/p&gt;

&lt;p&gt;Django (gdh/ˈdʒæŋɡoʊ/jang-goh) is a free, open source web application framework written in Python. A web framework is a set of components that help you develop websites more easily and quickly.&lt;/p&gt;

&lt;h3&gt;
  
  
  What happens when someone requests a website from your server?
&lt;/h3&gt;

&lt;p&gt;When a request arrives at the server, it is sent to Django. What he will try to do is find out what is really being requested. First you have to get the address of the site and try to find out how to proceed.&lt;/p&gt;

&lt;p&gt;At this point, Django's urlresolver is in charge of solving it (keep in mind that the address of a page is designated as URL - Uniform Resource Locator), so urlresolver makes sense.&lt;/p&gt;

&lt;p&gt;The truth is that we are talking about a function that is not so smart as it tries to look for patterns to find the URL. Django manages to corroborate each pattern from top to bottom and when it finds a match, Django passes each request to the function that is linked and called "view".&lt;/p&gt;

&lt;p&gt;You can get an idea if you put a postman carrying a message or letter into context. He is walking around and seeks to corroborate each room or house number with that of the letter he is carrying. If there's a turnout, he leaves the message there - it works the same way url resolve!&lt;/p&gt;

&lt;p&gt;With the view function there are several things to consider: you can look inside the database in order to find some information. Is it possible that someone has asked to modify some data? For example, the letter saying "Can you please modify the data in the job description? This is where the 'view' can check whether you have permission to do so, so the job description should be updated to say "Done! That's where the 'view' creates a response and Django seeks to forward it to the person's browser on the spot.&lt;/p&gt;

&lt;p&gt;Of course, the description shown has been simplified, but for now it's not necessary to know all the modalities. Simply loading a general idea is more than enough.&lt;/p&gt;

&lt;p&gt;That's why we won't go into so much detail, we'll just start with creating something in Django and you'll learn every relevant key along the way.&lt;/p&gt;

&lt;p&gt;From Django's website we can see some highlights, in which we can observe some websites such as National Geografic, Disqus, Instagram, Mozilla Foundation and Pinterest, which are websites with a very high traffic and use Django.&lt;/p&gt;

&lt;p&gt;In the next article, I will explain how to install Django.&lt;/p&gt;

&lt;p&gt;But now let me explain the advantages of using Django.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why use Django
&lt;/h3&gt;

&lt;p&gt;The main reasons for using Django are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;It's very fast: If you have a startup, are in a hurry to finish your project or simply want to reduce costs, with Django you can build a very good application in a short time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It comes well loaded: Whatever you need to do, it will already be implemented, you just have to adapt it to your needs. Whether it's because there are community modules, any Python package you find, or the applications Django comes with, they're very useful.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It's pretty safe: We can rest assured that Django implements some security measures by default, the most classic ones, so that there is no SQL Injection, no Cross site request forgery (CSRF) or JavaScript Clickjacking. Django handles all of this in a really simple way.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It's very scalable: we can go from very little to a huge application perfectly, an application that is modular, that works fast and is stable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It's incredibly flexible: It's true that at first Django started out as a framework for storing news for press sites, blogs and this style of website, but over time it has gained so much popularity that it can be used for any purpose you want.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Other advantages offered by Django
&lt;/h3&gt;

&lt;p&gt;Other benefits of Django that are not highlighted on the website are: &lt;/p&gt;

&lt;p&gt;Its ORM, its interface for accessing the database, since making queries with it is a wonder, is a very good tool.&lt;/p&gt;

&lt;p&gt;It comes standard with an administration panel, with which we can leave people without any technical knowledge handling important data in a very comfortable way.&lt;/p&gt;

&lt;h4&gt;
  
  
  Conclusions
&lt;/h4&gt;

&lt;p&gt;In general, if you have used Symfony in PHP or Ruby on Rails, Django is similar. If you like the ones above, I'm sure this one will, and if you like them, you should give it a try.&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
    </item>
    <item>
      <title>Javascript: What are Callbacks and how to use them</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Fri, 23 Oct 2020 08:02:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/javascript-what-are-callbacks-and-how-to-use-them-4n09</link>
      <guid>https://dev.to/salvietta150x40/javascript-what-are-callbacks-and-how-to-use-them-4n09</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.ma-no.org%2Fcache%2Fgalleries%2Fcontents-2064%2F960-400%2Fjavascript-callbacks-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.ma-no.org%2Fcache%2Fgalleries%2Fcontents-2064%2F960-400%2Fjavascript-callbacks-impjpg.webp" alt="What are Callbacks and how to use them"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is the use of Callbacks.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Callback?
&lt;/h2&gt;

&lt;p&gt;Simplifying, it is to pass a function as a parameter so that this function runs our parameter. You may have already done it in C#, PHP or Java: make your function/method return something to perform the action.This is what we usually do as programmers.&lt;/p&gt;

&lt;p&gt;In the following example, the function foo receives by parameter another function, which is the callback. The function foo is in responsible of executing the callback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function foo(callback) { 
 //do something
  callback();
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is important to take into account that when we pass a callback we only pass the definition of the function and do not execute it in the parameter. &lt;/p&gt;

&lt;p&gt;So, the container function chooses when to execute the callback.&lt;/p&gt;

&lt;p&gt;A very common example of callback is as a listening function of an event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showAlert(){
   alert('Alerta');
}  
button.addEventListener('click', showAlert);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, showAlert is a callback. We can also write the callback as an anonymous function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;button.addEventListener('click', function(){
  alert('Alerta');
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Callbacks are also used to "warn" when a function has finished doing something:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function foo(callback) {
   console.log("hello")
   callback();
}foo(function(){console.log("finished")});
→ hello
  finished

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The use of callback is also known as callback pattern, since it is essentially a pattern as it is a solution to common problems. In addition, the use of callbacks is related to functional programming, which specifies the use of functions as arguments. &lt;/p&gt;

&lt;p&gt;Callbacks can help not to repeat code and its maintenance, to get more specific functions and, in some cases, to improve the level of abstraction and code reading.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checking the asynchronous execution with callbacks
&lt;/h2&gt;

&lt;p&gt;The callbacks themselves are synchronous. In the following example, it is the container function that chooses when the callback is executed, and it is executed without causing another execution flow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function foo(val, callback){
 if(val == 1){
  callback(true);
}
 else{
  callback(false);
} 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Therefore, callbacks are very useful for handling asynchrony in JS. For example, they can be very useful when we are testing asynchronous elements. &lt;/p&gt;

&lt;p&gt;Let's see an example.&lt;/p&gt;

&lt;p&gt;Within a test, we create a setTimeOut (asynchronous method since it causes another execution flow). The test can work incorrectly because it does not wait for the asynchronous operation to be finished and it does not get executed. &lt;/p&gt;

&lt;p&gt;To make sure that the content of the setTimeOut is always executed, we pass a callback to it. Until the callback has been called, JS will not leave the test (i.e. the function).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it("checks something of the DOM", function (done) {
foo1();
foo2();
foo3();
function onTimeout() {
  expect(parseInt(element.innerHTML)).toEqual(x);
done();
}
setTimeout(onTimeout, 1000);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see what the order of execution is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it("restart the counter time", function (done) {
  console.log(1);
  foo1();
  console.log(2);
  foo2();
  console.log(3);
  foo3();
  console.log(4);
function onTimeout() {
console.log(5);
expect(parseInt(element.innerHTML)).toEqual(x);
console.log(6);
 done();
console.log(7);
}
console.log(8);
setTimeout(onTimeout, 1000);
console.log(9);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El orden de ejecución, al pasar el test, es el siguiente:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  1

  2

  3

  4

  8

  9

  5

  6

  7

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the done parameter we make sure that the number 5, 6 and 7 are always executed.&lt;br&gt;
Let's see the case where we don't pass callback to the test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it("restart the counter time", function () {
  console.log(1);
  foo1();
  console.log(2);
  foo2();
  console.log(3);
  foo3();
  console.log(4);
function onTimeout() {
console.log(5);
expect(parseInt(element.innerHTML)).toEqual(x);
console.log(6);
}
console.log(8);
setTimeout(onTimeout, 1000);
console.log(9);

});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The order of execution, when passing the test, is as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  1

  2

  4

  8

  9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Neither the 5th nor the 6th is ever executed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Callbacks to eliminate knowledge on the dependencies
&lt;/h2&gt;

&lt;p&gt;In a code, it is usual that there are functions that depend on other functions. When many parts of our code depend on other parts, it is easier for some methods to affect others without us having foreseen it or for any future change to be complex and laborious. In general, the less dependency, the better.&lt;/p&gt;

&lt;p&gt;There are several ways to eliminate dependency and one of them is the use of callbacks. This is not a common solution nor can we use it in every situation, but it can help us in certain cases.&lt;/p&gt;

&lt;p&gt;Through callbacks, we can reverse the dependency at the knowledge level and make one function unaware of the other function it is executing.&lt;/p&gt;

&lt;p&gt;Let's look at an example with a countdown:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var seconds = 20;function startCountDown(){
  setInterval(function(){
    seconds--;
    showSeconds();
  }, 1000);
}function showSeconds(){
   console.log(seconds);
}startCountDown()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The startCountDown function depends on the showSeconds() function. Every second, startCountDown executes the showSeconds function. If we want to minimize this dependency, we can make the startCountDown function unaware of the showSeconds function by passing it a callback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var seconds = 20;function startCountDown(onTimeChanged){
  setInterval(function(){
    seconds--;
    onTimeChanged();
  }, 1000);
}function showSeconds(){
  console.log(seconds);
}startCountDown(showSeconds);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
    <item>
      <title>How to Turn An Android Device Into a Retro Game Console</title>
      <dc:creator>Salvietta150x40</dc:creator>
      <pubDate>Wed, 14 Oct 2020 04:02:00 +0000</pubDate>
      <link>https://dev.to/salvietta150x40/how-to-turn-an-android-device-into-a-retro-game-console-5856</link>
      <guid>https://dev.to/salvietta150x40/how-to-turn-an-android-device-into-a-retro-game-console-5856</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z0MbQ56f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2047/960-400/retro-game-console-collection_1010-416-impjpg.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z0MbQ56f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2047/960-400/retro-game-console-collection_1010-416-impjpg.webp" alt="How to Turn An Android Device Into a Retro Game Console" width="800" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you like retro games and you want to set up your own system at home, a good way to do it is using Android. From emulators for Mega Drive, N64, GBA, PS1 or Super Nintendo, to other systems such as MAME, all of them are available in Android app format. And the truth is that they are verry practical.&lt;/p&gt;

&lt;p&gt;In addition, from some time to this part, we have also been able to see official relaunches of retro games in the Play Store, such as the Sega Forever classics, or the Final Fantasy and Dragon Quest sagas. Having said that, let's see how we can turn our phone, tablet or TV Box into a sort of Android console for retro games.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to turn your old Android phone into a classic game console
&lt;/h2&gt;

&lt;p&gt;The video games of the 80s and 90s are not usually very demanding, so if we have an old Android phone we can give it a new life if we decide to use it to connect to the TV and use it as a video console.&lt;/p&gt;

&lt;h3&gt;
  
  
  Things we will need
&lt;/h3&gt;

&lt;p&gt;To assemble the complete system we will need the following elements:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;An Android phone or tablet.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A USB C to HDMI adapter for the mobile phone and an HDMI cable to connect it to the TV.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If your mobile phone does not have a USB C port you will need to use another method to connect your mobile phone to the TV.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;An emulator or retrogaming suite.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The ROMs of the games we are interested in.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A gamepad or controller for video games (Bluetooth).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A charger to keep the device always on and not to run out of battery.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If we have a TV Box it is even easier, as we will not need any additional cable or adapter to connect the Android device to the TV.&lt;/p&gt;

&lt;h2&gt;
  
  
  The emulators
&lt;/h2&gt;

&lt;p&gt;Once we've got hold of all the components of our "Android console", it can take the longest time to find the right emulators. If you've heard of retro platforms, you'll probably have heard of the fabulous Recalbox. Unfortunately it is not a solution that is available on Android, although we can find multi-platform emulators such as RetroArch, which support several consoles at the same time.&lt;/p&gt;

&lt;h2&gt;
  
  
  The gamepad
&lt;/h2&gt;

&lt;p&gt;To achieve a proper gaming experience we will need a Bluetooth gamepad. We can take advantage of the PS4 controllers -see HERE to see how- or buy an Android-compatible controller. Nowadays there are manufacturers such as 8Bitdo that do real wonders, with retro gamepads of the highest quality and aesthetics.&lt;/p&gt;

&lt;p&gt;![How to Turn An Android Device Into a Retro Game Console](&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uE4FzsS_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2047/gamepad-compatible-with-android-for-retro-games.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uE4FzsS_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.ma-no.org/cache/galleries/contents-2047/gamepad-compatible-with-android-for-retro-games.jpg" alt="How to Turn An Android Device Into a Retro Game Console" width="720" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The games
&lt;/h2&gt;

&lt;p&gt;Now that we have the emulators and the gamepad, all we need to do is get hold of a few games. They are what is usually known as ROMs, which is basically the game compressed in a ZIP or RAR file.&lt;/p&gt;

&lt;p&gt;It is worth remembering that making backup copies of games or ROMs is legal as long as we are in possession of the original cartridge or game. Likewise, downloading ROMs of games that we do not have in physical format is completely illegal.&lt;/p&gt;

&lt;p&gt;Alternatively, we can also "rip" our own ROMs using a device such as Retrode, thanks to which we can extract the content of our cartridge and download it to a PC via a USB connection.&lt;/p&gt;

&lt;p&gt;That said, there are also freeware ROMs from independent developers that also do not break any copyright, and in some cases are really good.&lt;/p&gt;

&lt;h2&gt;
  
  
  Retrogaming in Android through KODI
&lt;/h2&gt;

&lt;p&gt;Another alternative to play video games on Android is KODI. From version 18 of the application, it incorporates a new tool called Retroplayer.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to configure the RetroArch Android emulator suite
&lt;/h2&gt;

&lt;p&gt;The idea of using RetroArch is to have a single central tool that allows us to emulate all the games. This way we can do everything from one place without having to constantly open and close apps.&lt;/p&gt;

&lt;p&gt;There are currently 2 versions of RetroArch, a standard version for older devices and a 64-bit version for more modern Android terminals. Therefore, it is advisable to check which version we need before installing the app. Normally we will notice it right away, because if our device is not compatible, a clear message will appear when we try to download it from the Play Store.&lt;/p&gt;

&lt;p&gt;Once we have the application installed, RetroArch will ask us for permission to scan our internal memory. In this way, it will detect the folders where the game ROMs are located.&lt;/p&gt;

&lt;p&gt;Next, we will proceed to download the emulators that we will use. To do this, we will "Load core -&amp;gt; Download core" and select the emulators we are interested in. There are more than fifty to choose from.&lt;/p&gt;

&lt;p&gt;Finally, return to the main menu and click on "Load content". We look for the ROM of the game we want to load with the corresponding emulator, and we will be ready for a good retrogaming session.&lt;/p&gt;

&lt;p&gt;Among its various features, RetroArch has an online update tool, online multiplayer for those games that support it, and above all, the possibility of saving the game. This works even with games that originally did not have a save function, allowing us to stop and resume games when it is most convenient for us.&lt;/p&gt;

&lt;h2&gt;
  
  
  ClassicBoy as an alternative
&lt;/h2&gt;

&lt;p&gt;Another emulation suite that is also available in Android is ClassicBoy. It supports up to 8 different emulators, and has customizable controls, although in its free version it does not give the option to save the game. Something we can solve if we get the premium version, which costs about 3.5 euros.&lt;/p&gt;

&lt;p&gt;Personally I think that in general it is not as good as RetroArch, but it has some interesting things like support for up to 4 players, gesture control and accelerometer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dedicated Emulators: Citra, NES Nostalgia and MAME4droid
&lt;/h2&gt;

&lt;p&gt;Finally, mention that there is also the possibility of installing specific system emulators. For example, in recent months Citra, the Android emulator for the classic Nintendo 3DS, has become really popular. On the other hand, if the only thing we are interested in is playing 8-bit NES titles then we should definitely install Nostalgia NES, an Android emulator that has been struggling for years and works really well. Likewise, if we prefer the old-fashioned arcade games, there is nothing like trying MAME4droid, another of those emulators that make school.&lt;/p&gt;

&lt;p&gt;In short, Android has emulators for most of the classic systems, some better than others, but there is no doubt that there is a community that keeps bringing out new things to make the most of the playable part of our mobile devices.&lt;/p&gt;

</description>
      <category>games</category>
      <category>retrogames</category>
      <category>android</category>
    </item>
  </channel>
</rss>
