How to Create a Favicon That Changes Automatically
Strategy

How to Create a Favicon That Changes Automatically


I found this Free Favicon Maker the other day. It’s a nice tool to make a favicon (true to its name), but unlike other favicon generators, this one lets you create one from scratch starting with a character or an emoji. Naturally, I was curious to look at the code to see how it works and, while I did, it got me thinking in different directions. I was reminded of something I read that says it is possible to dynamically change the favicon of a website. That’s actually what some websites use as a sort of notification for users: change the favicon to a red dot or some other indicator that communicates something is happening or has changed on the page.

I started browsing the emojis via emojipedia.org for inspiration and that’s when it struck: why not show the time with a clock emoji (????) and other related favicons? The idea is to check the time every minute and set the favicon with the corresponding clock emoji indicating the current time.

We’re going to do exactly that in this article, and it will work with plain JavaScript. Since I often use Gatsby for static sites though, we will also show how to do it in React. From there, the ideas should be usable regardless of what you want to do with your favicon and how.

Here’s a function that take an emoji as a parameter and returns a valid data URL that can be used as an image (or favicon!) source:

// Thanks to https://formito.com/tools/favicon
const faviconHref = emoji =>
  `data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22256%22 height=%22256%22 viewBox=%220 0 100 100%22><text x=%2250%%22 y=%2250%%22 dominant-baseline=%22central%22 text-anchor=%22middle%22 font-size=%2280%22>${emoji}</text></svg>`

And here’s a function that targets the favicon <link> in the <head> and changes it to that emoji:

const changeFavicon = emoji => {
  // Ensure we have access to the document, i.e. we are in the browser.
  if (typeof window === 'undefined') return

  const link =
    window.document.querySelector("link[rel*='icon']") ||
    window.document.createElement("link")
  link.type = "image/svg+xml"
  link.rel = "shortcut icon"
  link.href = faviconHref(emoji)

  window.document.getElementsByTagName("head")[0].appendChild(link)
}

(Shout out to this StackOverflow answer for that nice little trick on creating the link if it doesn’t exist.)

Feel free to give those a try! Open up the DevTools JavaScript console, copy and paste the two functions above, and call changeFavicon("????"). You can do that right on this website and you’ll see the favicon change to that awesome dancing emoji.

Back to our clock/time project… If we want to show the emoji with the right emoji clock showing the correct time, we need to determine it from the current time. For example, if it’s 10:00 we want to show ????. If it’s 4.30 we want to show ????. There aren’t emojis for every single time, so we’ll show the best one we have. For example, between 9:45 to 10:14 we want to show the clock that shows 10:00; from 10:15 to 10:44 we want to show the clock that marks 10.30, etc.

We can do it with this function:

const currentEmoji = () => {
  // Add 15 minutes and round down to closest half hour
  const time = new Date(Date.now() + 15 * 60 * 1000)

  const hours = time.getHours() % 12
  const minutes = time.getMinutes() < 30 ? 0 : 30

  return {
    "0.0": "????",
    "0.30": "????",
    "1.0": "????",
    "1.30": "????",
    "2.0": "????",
    "2.30": "????",
    "3.0": "????",
    "3.30": "????",
    "4.0": "????",
    "4.30": "????",
    "5.0": "????",
    "5.30": "????",
    "6.0": "????",
    "6.30": "????",
    "7.0": "????",
    "7.30": "????",
    "8.0": "????",
    "8.30": "????",
    "9.0": "????",
    "9.30": "????",
    "10.0": "????",
    "10.30": "????",
    "11.0": "????",
    "11.30": "????",
  }[`${hours}.${minutes}`]
}

Now we just have to call changeFavicon(currentEmoji()) every minute or so. If we had to do it with plain JavaScript, a simple setInterval would make the trick:

// One minute
const delay = 60 * 1000

// Change the favicon when the page gets loaded...
const emoji = currentEmoji()
changeFavicon(emoji)

// ... and update it every minute
setInterval(() => {
  const emoji = currentEmoji()
  changeFavicon(emoji)
}, delay)

The React part

Since my blog is powered by Gatsby, I want to be able to use this code inside a React component, changing as little as possible. It is inherently imperative, as opposed to the declarative nature of React, and moreover has to be called every minute. How can we do that?

Enter Dan Abramov and his amazing blog post. Dan is a great writer who can explain complex things in a clear way, and I strongly suggest checking out this article, especially if you want a better understanding of React Hooks. You don’t necessarily need to understand everything in it — one of the strengths of hooks is that they can be used even without fully grasping the internal implementation. The important thing is to know how to use it. Here’s how that looks:

import { useEffect } from "react"
import useInterval from "./useInterval"

const delay = 60 * 1000

const useTimeFavicon = () => {
  // Change the favicon when the component gets mounted...
  useEffect(() => {
    const emoji = currentEmoji()
    changeFavicon(emoji)
  }, [])

  // ... and update it every minute
  useInterval(() => {
    const emoji = currentEmoji()
    changeFavicon(emoji)
  }, delay)
}

Finally, just call useTimeFavicon() in your root component, and you are good to go! Wanna see it work? Here’s a deployed CodePen Project where you can see it and here’s the project code itself.

Wrapping up

What we did here was cobble together three pieces of code together from three different sources to get the result we want. Ancient Romans would say Divide et Impera. (I’m Italian, so please indulge me a little bit of Latin!). That means “divide and conquer.” If you look at the task as a single entity, you may be a little anxious about it: “How can I show a favicon with the current time, always up to date, on my React website?” Getting all the details right is not trivial.

The good news is, you don’t always have to personally tackle all the details at the same moment: it is much more effective to divide the problem into sub-problems, and if any of these have already been solved by others, so much the better!

Sounds like web development, eh? There’s nothing wrong with using code written by others, as long as it’s done wisely. As they say, there is no need to reinvent the wheel and what we got here is a nice enhancement for any website — whether it’s displaying notifications, time updates, or whatever you can think of.



Source link

npm ruin dev | CSS-Tricks
Strategy

npm ruin dev | CSS-Tricks


In 2020, I rediscovered the enjoyment of building a website with plain ol’ HTML, CSS, and JavaScript — no transpilin’, no compilin’, no build tools other than my hands on the keyboard.

Seeing as my personal brand could be summed up “so late to the game that the stadium has been demolished,” I decided to start a podcast in 2020. It’s the podcast of my agency, Clearleft, and it has been given the soaringly imaginative title of The Clearleft Podcast. I’m really pleased with how the first season turned out. I’m also really pleased with the website I put together for it.

The website isn’t very big, though it will grow with time. I had a think about what the build process for the site should be and after literally seconds of debate, I settled on a build process of none. Zero. Nada.

This turned out to be enormously liberating. It felt very hands-on to write the actual HTML and CSS that will be delivered to end users, without any mediation. I felt like I was getting my hands into the soil of the site.

CSS has evolved so much in recent years—with features like calc()  and custom properties—that you don’t have to use preprocessors like Sass. And vanilla JavaScript is powerful, fully-featured, and works across browsers without any compiling.

Don’t get me wrong—I totally understand why complicated pipelines are necessary for complicated websites. If you’re part of a large team, you probably need to have processes in place so that everyone can contribute to the codebase in a consistent way. The more complex that codebase is, the more technology you need to help you automate your work and catch errors before they go live.

But that setup isn’t appropriate for every website. And all those tools and processes that are supposed to save time sometimes end up wasting time further down the road. Ever had to revisit a project after, say, six or twelve months? Maybe you just want to make one little change to the CSS. But you can’t because a dependency is broken. So you try to update it. But it relies on a different version of Node. Before you know it, you’re Bryan Cranston changing a light bulb. You should be tweaking one line of CSS but instead, you’re battling entropy.

Whenever I’m tackling a problem in front-end development, I like to apply the principle of least power: choose the least powerful language suitable for a given purpose. A classic example would be using a simple HTML button element instead of trying to recreate all the native functionality of a button using a div with lashings of ARIA and JavaScript. This year, I realized that this same principle applies to build tools too.

Instead of reaching for all-singing all-dancing toolchain by default, I’m going to start with a boring baseline. If and when that becomes too painful or unwieldy, then I’ll throw in a task manager. But every time I add a dependency, I’ll be limiting the lifespan of the project.

My new year’s resolution for 2021 will be to go on a diet. No more weighty node_modules folders; just crispy and delicious HTML, CSS, and JavaScript.



Source link

mysql
Strategy

Building Server in Julia and Connecting to a Database


Introduction

With the growing popularity of the internet, building a web server has been an absolutely required skillset for any developer. However, there are popular frameworks in some languages available (like Node.js or Django) to build the backend. Still, Julia, being a relatively new language, also provides a framework for the same purpose. Julia is still under active development phase and has closer compiler performance than C.  Developers who have already implemented a machine learning or some data processing algorithm in Julia can now use the Julia Genie framework to expose APIs as well, which would help them use the same stack for the whole backend.

Installing Julia

If Julia is already installed in the system, typing $julia --version in the terminal should give Julia installed locally. Otherwise, official Julia documentation can be referred for installation. If installed properly, typing $julia in the terminal should start Julia in REPL mode.

Installing Genie

Installing Genie is the same as installing any Julia library. Typing Pkg.add("Genie") in REPL would install the Genie framework. Importing the package is performed by using Genie.

Getting a Basic Server Running

Let’s create a working directory test_server and an empty file named server.jl inside test_server.

Starting a server using Genie is fairly simple. up(port_number, async = false) function starts a server listening to the mentioned port number. Type the following snippet in the server.Jl and save.

Now open a terminal from the test_server directory and start Julia REPL. Typing include("server.jl") in REPL would start the server in port number 8001. Opening http://localhost:8001/path in a browser would show the text Hello.

Adding More Routes

Let’s take a use case of creating new users and getting a list of all existing users. For this we would need 2 APIs:

  1. One for creating a new user, which would be using the POST method
  2. Another for getting a list of existing users who would be using GET

So, modify the server.jl file with following content.

Accessing Request Parameters

We need to access the parameters and their values sent as payload in request body. To access a parameter we have getpayload(:param_key, "default_value") or postpayload(:param_key, "default_value") depending on whether it is a GET or POST request. Here param_key is the key of the parameter, and default_value is the value that would be considered if the parameter is not set in the request body.

Let’s modify our server.jl with the following snippet.

Installing MySQL

We would be using MySQL for Database. Needless to say MySQL should be installed in system. Otherwise the official installation guide can be followed. Once MySQL server is up and running locally, create an empty database named test_user. From the MySQL command-line client, it would look like this.

mysql

Accessing MySQL Database

We can access and run query in a MySQL server using its Julia client. It can be installed by Pkg.add("MySQL") from Julia REPL. To initiate a connection to server, we can use the following function.

This would return a connection object, which can be used to run a query.

Connecting the Dots

Summing all the above things up, we can create a Genie server, which would be inserting data to the Database upon creating a new user. To respond to a request of getting to respond query from the database and return the list of users as response.

Our server.Jl would look something like this. Before running the server.jl, install JSON, DataFrames and JSONTables in Julia.

Now we are ready to start the server by running include("server.jl").

Requesting Our Server

Our motive will not be complete until we would be requesting our server and get response from it. So for this purpose, we would be using Postman. If not installed, it can be installed following this guide.

Now, we would have to send a POST request on http://127.0.0.1:8001/createuser from Postman. The request body should have two parameters called user_id and user_status. The response should return  the text POST OK.POST OK

To send a GET request on http://127.0.0.1:8001/getusers, no request body is needed. However it is better to set Accept: application/json in our GET request header, so that the server’s response is parsed as a JSON. The response should return list of all existing users in our Database.

JSON server

Conclusion

This way, making a basic web server would be pretty easy in Julia; however, to serve a real-world use case will never be this much simple. But, hope this article helps you to have a starting point. Thanks and Happy Coding!



Source link

Examples of Lynn Fischer
Strategy

Very Extremely Practical CSS Art


I’ve always enjoyed the CSS art people create, but I’ve never ventured into it much myself. I’m familiar with many of the tricks involved, but still find it surprising every time: the way people are able to make such fluid and beautiful images out of little boxes. I always end up digging around in dev tools to see how things are done, but I had never seen the process unfold.

Any time CSS art starts getting attention, there is always someone around to say “that’s not practical” or “just use SVG” or something similarly dismissive and boring. It’s a terrible argument, even if it was true — no one is required to be Practical At All Times. What a terrible world that would be.

In October, I took the time to watch Lynn Fisher (Twitter, CodePen), one of my favorite CSS artists, live-stream her single-div process. Somewhere in the back of my mind, I assumed single-div artwork relied on highly complicated box-shadows—almost a pixel-art approach. I’m not sure where that idea came from, I probably saw someone do it years ago. But her process is much more “normal” and “practical” than I even realized: a number of reasonably layered, sized, and positioned background gradients.

Examples of Lynn Fischer's single div projects: repeated polar bears, plants on a shelf, a blinking light, and a tiny electronic piano.

Wait. I know how to do that. It’s not the technique that’s magical—it’s the audacity of turning a few gradients into a block of cheese with cake inside!

I’ve used all these properties before on client projects. I’ve created gradients, layered images, sized them, and positioned them for various effects. None of that is new, or complicated, or radical. I really didn’t learn anything at all about the CSS itself. But it had a huge impact on my perception of what I could accomplish with those simple tools. 

Within a few weeks, I was using that in production. Again, it’s nothing fancy or complicated—the perfect low-hanging fruit where a custom SVG feels just slightly too bulky. Here’s the effect I created, for a personal project, with a few custom properties to make adjustment easier:

Last week we used a similar trick as part of a Very Practical & Official client component library. It was Stacy Kvernmo’s idea, and it worked great.

Thanks Lynn, and all you other fabulous CSS Artists! Thanks for showing us all how much farther we can push this language that we love so much, and the Very Serious tools we use every day.





Source link

A Detailed Breakdown of HTML Form Event Attributes
Strategy

A Detailed Breakdown of HTML Form Event Attributes


Don’t aspire to make a living, aspire to make a difference.

– Denzel Washington

Introduction

HTML forms allow users on a web page to enter data that will be sent to a server for processing. HTML forms are a powerful way of interacting with a web application. They include various elements called controls like (Text Input, Checkboxes, Radio Box, Select Box, e.t.c).

The HTML forms are enclosed inside a <form></form> element. The <form> element has various attributes, some of which includes the action attribute, the target attribute and the method attribute.

The Action Attribute

The action attribute helps to determine the type of form data that will be sent to the server after the submission of a form.

From the above code, the form data is sent to a file called “testpage.php” with the help of the action attribute.

The Target Attribute

This attribute specifies to the browser the particular page to display the response that is received once the form has been submitted.

Also, The Target attribute can have the values below:

  • The response is displayed in a new browser window or tab.
  • The response is displayed in the current window. This is the default value of the Target attribute.
  • The response is displayed in the parent frame
  • The response is displayed in the full body of the window
The Method Attribute

The Method attribute specifies the particular Hypertext Transfer Protocol (HTTP) method to be used when submitting form data.

There are two types of HTTP method attribute that can be used with the <form> element. They include the  GET and POST.

The GET Attribute
  • The example above uses the GET method when submitting the form data.
The POST Attribute
  • The example above uses the POST method when submitting the form data.

Also, one of the most used elements in an HTML form is the <input> tag. The <input> tag can be displayed in so many ways within the HTML form. Some of which includes:

Type Description
<input type=”text”> Displays a single-line text input field. It is the default type of the input element.
<input type=”radio”> Shows a radio button (for selecting one of many choices).
<input type=”checkbox”> Displays a checkbox (for selecting zero or more of many choices).
<input type=”submit”> Shows a submit button (for submitting the form).
<input type=”button”> Displays a clickable button.

Now that we’ve covered the basics of the HTML form, let us dive into the various form events.

HTML Form Events

1). onblur Event

The onblur event renders when an object loses its focus. The onblur event is mostly used with form validation, that is, when a user leaves a form field.

SYNTAX in HTML

Example

Here, we will create an input field that displays an alert box once the input field loses focus,

index.html

Above we have a function called blurFunction() which is declared inside an onblur attribute. Then we have our script tag linked top our JavaScript page, where we will perform the alert operation.

app.js

In the JavaScript file, we:

  • Accessed the input field by its id called myInput inside the blurFunction function.
  • Declared a variable called blurry
  • Then we created a condition that if the value typed in the form is called blurry, then an alert box should pop up once the input field loses focus.

RESULT

 

2). onchange Event

The onchange event occurs when the value of an element is changed. It is used in HTML elements such as <input > <select> and <textarea>.

SYNTAX in HTML

Example

Here, we will create a select element that returns different values on the DOM, based on the change event.

index.html

In the HTML page, we have a select element that shows various options with their values. The two important things to take note of here is:

  • The clubSelect() function in the onchange event attribute.
  • The div that contains the result class. This is where we will display the value of our event.

app.js

Here what we simply did was:

  • Declare the clubSelect() function created in the HTML page. This gives us access to the change event.
  • Create a result variable that accessed the .result class.
  • Assigned the result variable to the textContent method, which helps us to set a given text to the node like so.

RESULT

 

3). oncontextmenu Event

The oncontextmenu event performs its action when the user right-clicks the mouse on an object on the window. The oncontextmenu event is supported in all browsers.

SYNTAX in HTML

Example

In this example, we will be displaying an alert box within a div when we right-click, instead of the context menu options.

index.html

In the HTML file, we have a div that contains the oncontextmenu event attribute. The attribute contains the function called myAlert(), which will be used in the JavaScript file to create the alert box.

app.js

In the app.js file, we called the myAlert() function and declared an alert box within it when the oncontextmenu is fired within the div.

style.css

RESULT

4). onfocus Event

The onfocus event fires when a user sets the focus of the mouse on a particular element on the web page. It is the opposite of the onblur event.

It is mostly used with the with <input>, <select>, and <a> HTML elements.

SYNTAX in HTML

Example

Here we will display an alert box when the input field is in focus.

index.html

In the file above, we:

  • declared the onfocus event inside an input element.
  • created a value attribute with the word focus
  • Then we linked the file to out JavaScript file, where the magic happens.

app.js

In the app.js file we:

  • Called the focusFunction() function.
  • Created the val and focus variables. The val variable accessing the input field, while the focus variable holds the word focus.
  • Then finally, we created a condition that says if the value of the form contains the word “focus” and the input field is in an onfocus event state, an alert box should be displayed.

RESULT

 

 

5). oninput Event

The oniput event fires when the value of a text element like the <input> or <textarea> is changed. Similar to the onchange event, the main difference is that the input event gets triggered immediately when there is a change, whereas the onchange event occurs only when the element has lost focus.

SYNTAX in HTML

Example

Here, we will display the value of the input field on the page as the value gets changed.

index.html

Above we:

  • Created an input tag. Inside which we have an id called “myInput“, which we will refer to in the JavaScript file.
  • We also have the oniput event attribute declared.
  • As well as a div containing the id called “demo”.

app.js

The app.js file is straight forward. All we did was:

  • Refer to our myFuction() function from the HTML page.
  • Declared a variable called values, that accesses the input element.
  • Then we accessed the div with the id of demo, which is where we will display the text from the input field.
  • With the help of the textContent method, we can assign the texts to the div tag.

RESULT

 

6). oninvalid Event

The oninvalid event occurs when a submittable input element is invalid and does not meet certain conditions. In most case, an error message is shown stating why the input submission is not valid.

SYNTAX in HTML

Example

Here we display an alert box that shows a message when an empty is submitted in the input field.

index.html

From the HTML file above, we created an input field that is expected to take in a username. Inside the input field, we have a function called testValidity(). This function will be used to display our alert box in the JavaScript file.

app.js

Here we simply reference the function called testValidity() set inside the oninvalid event attribute in the HTML file. Anytime the form is submitted with an input empty filed, the alert box will display the message “Field Cannot Be Empty”.

RESULT

 

7). onreset Event

The onreset event occurs when a user clicks on a reset button within a form. This set the form back to the predefined state.

SYNTAX in HTML

Example

In this example, we will create an input field that gets cleared once the reset button is clicked. Once this event fires, we will log the time in which the form was clicked on the browser page.

index.html

Here we:

  • Created a form tag that takes in an id and an onreset event attribute.
  • Created an input field that takes in some text.
  • A reset button that sets the state of the form to empty.
  • Lastly, we create a p tag that carries an id calleddisplay to show the time the form was reset.

app.js

In the JavaScript file we simply:

  • Made reference to our resetForm() function.
  • Accessed the display id from the HTML page.
  • Next, we append the textContent method to display the current date as at when the rest button is clicked.

RESULT

 

8). onsearch Event

The onsearch event occurs when a user initiates a search inside an <input> element. The <input> will have a type of “search” for this to get fired.

SYNTAX in HTML

Example

We will create an input field that allows users to search once the enter button is pressed. The searched value will be shown on the page.

index.html

In the index.html file, we:

  • Created an input element that has an id called searching. We also declared the onsearch event attribute that takes in a function
  • Lastly, we created a p element that has an id called to display to help show the value of the input field on the page.

app.js

In the app.js file, we:

  • Made reference to the function called searchInput() declared in the HTML file.
  • Accessed the id’s in the HTML file.
  • Lastly, we displayed the value of the input field on the page once the ENTER key is pressed.

RESULT

 

9). onselect Event

The onselect event only occurs when a particular text has been selected on either the <input type=”text”> or <textarea> elements.

SYNTAX in HTML

Example

In this example, we will create an input field. The goal is to display the number of text selected in the input field inside an alert pop box.

index.html

In the index.html file above, we:

  • Created an input field which contains the value “Happiness is Free”.
  • Also, we have our onselect attribute with a function called selected()

app.js

Here we:

  • Referenced the selected() function from the HTML page.
  • Created a variable called highlighted. Inside this variable, we get the value of text inside the input field, while getting the index at the beginning and the end of the input field.
  • Lastly, when the text gets selected, we display an alert box showing the number of words that were selected in the input field.

RESULT

 

10). onsubmit Event

The onsubmit event gets triggered when a form is submitted on a page, by a user.

SYNTAX in HTML

Example

In this example, we will be submitting the values inside a form. We will get a confirmation message from another page.

index.html

 

In the index.html page, we:

  • Have a form element with an action that routes to a submit.html page when the form is submitted.
  • Inside the form, we also have the onsubmit event attribute, which takes in the function called myFunction()
  • Also, have two input elements. One takes in the name input, while the other is a button that helps us submit the form.

app.js

 

In the JavaScript file, we simply called the myFunction() declared in the HTML page, then we created an alert box that displays a message when the form is submitted.

submit.html

The submit.html file is the page that gets displayed when the form is submitted.

RESULT

 

Conclusion

This article aims to cover the basics of how the HTML form event attribute work.

Also, here is the GitHub link to the code examples used in the article.



Source link