Hongkiat https://www.hongkiat.com/blog/author/preethi/ Tech and Design Tips Wed, 14 Aug 2024 07:21:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 1070734 Comprehensive Guide to CSS Pseudo-Classes and Their Usage https://www.hongkiat.com/blog/definite-guide-css-pseudoclasses/ https://www.hongkiat.com/blog/definite-guide-css-pseudoclasses/#comments Thu, 15 Aug 2024 10:00:48 +0000 https://www.hongkiat.com/blog/?p=26671 Whether you’re new to CSS or have years of experience, you’ve likely encountered pseudo-classes. The most commonly recognized pseudo-class is probably :hover, which allows us to style an element when it’s in the hover state, such as when a mouse pointer hovers over it. Building on concepts from our previous discussions on margin:auto and CSS…

The post Comprehensive Guide to CSS Pseudo-Classes and Their Usage appeared first on Hongkiat.

]]>
Whether you’re new to CSS or have years of experience, you’ve likely encountered pseudo-classes. The most commonly recognized pseudo-class is probably :hover, which allows us to style an element when it’s in the hover state, such as when a mouse pointer hovers over it.

Building on concepts from our previous discussions on margin:auto and CSS Floats, this post provides a detailed examination of pseudo-classes. We’ll explore what pseudo-classes are, how they function, how they can be categorized, and how they differ from pseudo-elements.

Understanding Pseudo-Classes

A pseudo-class is a keyword added to CSS selectors to define a specific state of an HTML element. You can add a pseudo-class to a CSS selector using the colon syntax :, like this: a:hover { ... }.

A CSS class is an attribute applied to HTML elements to enforce the same style rules, such as for top menu items or sidebar widget titles. Essentially, CSS classes group or classify HTML elements that share common traits.

Pseudo-classes are similar to CSS classes because they also apply style rules to elements with shared characteristics. However, while standard classes are user-defined and visible in the source code (e.g., <div class="myClass">), pseudo-classes are applied by user agents (e.g., web browsers) based on the current state of the HTML element.

The Role of Pseudo-Classes

The purpose of regular CSS classes is to classify or group elements. Developers group elements based on intended styling, creating classes like “menu-items,” “buttons,” or “thumbnails” to ensure consistent design across similar elements. These groupings are based on characteristics defined by the developers.

For example, a developer might use a <div> as a thumbnail and classify it with a “thumbnail” class.

 <div class="thumbnail">[...]</div>

However, HTML elements possess inherent characteristics based on their state, position, nature, and interaction with the page and user. These traits are not typically marked in HTML code, but can be targeted with pseudo-classes in CSS. Examples include:

  • An element that is the last child within its parent element
  • A link that has been visited
  • An element that has gone fullscreen

These are the types of characteristics typically addressed by pseudo-classes. To better understand the difference between classes and pseudo-classes, let’s consider using the class .last to identify the last elements in various parent containers.

 <ul>
 <li>item 1</li>
 <li>item 2</li>
 <li>item 3</li>
 <li class="last">item 4</li>
 </ul>
 
 <select>
 <option>option 1</option>
 <option>option 2</option>
 <option>option 3</option>
 <option class="last">option 4</option>
 </select>

You can style these last-child elements with the following CSS:

 li.last {
   text-transform: uppercase;
 }
 
 option.last {
   font-style: italic;
 }

But what happens when the last element changes? You’ll need to manually update the .last class from the previous last element to the new one.

This hassle of updating classes can be avoided for certain common characteristics. For example, using a predefined :last-child pseudo-class is highly beneficial. With this, there’s no need to mark the last element in the HTML code, and you can still style it with the following CSS:

 li:last-child {
   text-transform: uppercase;
 }
 
 option:last-child {
   font-style: italic;
 }

Main Types of Pseudo-Classes

CSS offers a variety of pseudo-classes that allow developers to target elements based on specific characteristics that might otherwise be difficult to access. You can find a comprehensive list of standard pseudo-classes on MDN.

1. Dynamic Pseudo-Classes

Dynamic pseudo-classes are applied to HTML elements dynamically, based on the state they transition into due to user interactions. Some examples include :hover, :focus, :link, and :visited, all of which are commonly used with the <a> anchor tag.

 a:visited {
   color: #8D20AE;
 }
 
 .button:hover,
 .button:focus {
   font-weight: bold;
 }
2. State-Based Pseudo-Classes

State-based pseudo-classes are applied to elements when they are in a specific static state. Common examples include:

  • :checked for checkboxes (<input type="checkbox">)
  • :fullscreen to target any element currently displayed in full-screen mode
  • :disabled for elements that can be disabled, such as <input>, <select>, and <button>.

The :checked pseudo-class is particularly popular, as it indicates whether a checkbox is selected.

 .checkbox:checked + label {
   font-style: italic;
 }
 
 input:disabled {
   background-color: #EEEEEE;
 }
3. Structural Pseudo-Classes

Structural pseudo-classes target elements based on their position within the document structure. Some of the most commonly used examples include :first-child, :last-child, and :nth-child(n). These can be used to style specific child elements based on their position within a container. Another example is :root, which targets the highest-level parent element in the DOM.

4. Miscellaneous Pseudo-Classes

There are also pseudo-classes that don’t fit neatly into other categories, such as:

  • :not(x), which selects elements that don’t match the specified selector x
  • :lang(language-code) for targeting elements based on the language of their content
  • :dir(directionality), which selects elements with content in a specific directionality (e.g., left-to-right or right-to-left).
 p:lang(ko) {
   background-color: #FFFF00;
 }
 
 :root {
   background-color: #FAEBD7;
 }

nth-child vs nth-of-type Pseudo-Classes

One of the most challenging aspects of pseudo-classes is understanding the difference between the :nth-child and :nth-of-type pseudo-classes.

Both of these are structural pseudo-classes that target specific elements within a parent element (container), but they do so in distinct ways.

Assume n is 2. The :nth-child(n) selector targets an element that is the second child of its parent element, regardless of the type of element. On the other hand, :nth-of-type(n) targets the second occurrence of a specific type of element (e.g., a paragraph) within the parent element.

Let’s take a look at an example to illustrate this difference:

 /* Styles the second child element inside its parent, which can be of any type */
 p:nth-child(2) {
   color: #1E90FF; /* Light blue */
 }
 
 /* Styles the second paragraph inside its parent element */
 p:nth-of-type(2) {
   font-weight: bold;
 }

Now, let’s see how this CSS affects the HTML in two different scenarios.

Case 1

In Case 1, the second element inside a <div> is an unordered list, so the :nth-child(2) rule does not apply to the paragraphs. Although the unordered list is the second child, it is not a paragraph.

If, however, the parent element contains a second paragraph, the :nth-of-type(2) rule will apply, since this rule specifically targets <p> elements and ignores other types of elements (like unordered lists) within the parent element.

In our example, the :nth-of-type(2) rule will style the second paragraph, which is Child 3 in this case.

 <!-- Case 1 -->
 <div>
   <p>Paragraph 1, Child 1</p>
   <ul>Unordered List 1, Child 2</ul>
   <p>Paragraph 2, Child 3</p>
 </div>
Example of Nth-Pseudoclass Case 1
Case 2

In Case 2, we move the unordered list to the third position, placing the second paragraph before it. Now, both the :nth-child(2) and :nth-of-type(2) rules will apply, as the second paragraph is both the second child of its parent <div> and the second <p> element.

 <!-- Case 2 -->
 <div>
   <p>Paragraph 1, Child 1</p>
   <p>Paragraph 2, Child 2</p>
   <ul>Unordered List 1, Child 3</ul>
 </div>
Example of Nth-Pseudoclass Case 2

To explore the differences between :nth-child and :nth-of-type further, CSS Tricks has a great post on the topic. If you use SASS, Family.scss can help you create complex nth-child based elements.

Pseudo-Classes vs Pseudo-Elements

When discussing pseudo-classes, it’s crucial to understand how they differ from pseudo-elements to avoid confusion.

Pseudo-elements, like ::before and ::after (see this tutorial on how to use them), are also added by user agents and can be targeted and styled with CSS in a manner similar to pseudo-classes.

The key difference is that pseudo-classes are used to select HTML elements that already exist in the document tree, though they may not be explicitly marked, while pseudo-elements allow us to style elements that don’t typically exist in the DOM on their own. Examples include ::before and ::after, or parts of existing elements like ::first-letter and ::placeholder.

There is also a difference in syntax: pseudo-elements are generally written with double colons ::, while pseudo-classes use a single colon :. This can be confusing because, in CSS2, pseudo-elements were also marked with a single colon—browsers still support this older syntax.

Additionally, there are differences in how we can target pseudo-classes and pseudo-elements with CSS.

1. Their Place in the CSS Selector Sequence

Pseudo-elements must appear after the sequence of selectors, while pseudo-classes can be positioned anywhere within the CSS selector sequence.

For instance, you can target the last list item in a <ul> element in two different ways:

<ul>
  <li class="red"></li>
  <li></li>
  <li class="red"></li>
  <li class="red"></li>
</ul> 
ul > :last-child.red {
  color: #B0171F;
}

OR

ul > .red:last-child {
  color: #B0171F;
}

The first selector targets the last child inside the <ul> element that has the class .red, while the second selector targets the last child among the elements that possess the .red class inside <ul>. As you can see, the position of the pseudo-class can vary.

Let’s attempt something similar with pseudo-elements.

ul > .red::after {
  display: block;
  content: 'red';
  color: #B0171F;
}

The CSS above is valid, and the text “red” will appear after the <li> items with the class .red.

However, the following code will not work because we cannot change the position of a pseudo-element within the selector sequence.

ul > ::after.red {
  display: block;
  content: 'red';
  color: #B0171F;
}
2. Number of Occurrences in a Selector Sequence

Only one pseudo-element can be used per selector, whereas pseudo-classes can be combined as long as the combination makes sense. For example, to target first-child elements that are also read-only, you can combine the pseudo-classes :first-child and :read-only as follows:

:first-child:read-only {
  color: #EEEEEE;
}

jQuery Selector Extensions

Not all selector syntax that includes a : is a proper CSS pseudo-class. If you’ve used jQuery, you might be familiar with selectors like $(':checkbox'), $(':input'), and $(':selected').

It’s important to note that these are not CSS pseudo-classes being targeted by jQuery. Instead, they are known as jQuery selector extensions.

jQuery selector extensions allow you to target HTML elements with simpler keywords. Many of these extensions are shorthand for combinations of standard CSS selectors, represented by a single keyword.

/* Change the font of all input-related HTML elements,
   like button, select, and input */
 
$( ":input" ).css("font-family","courier new");

The post Comprehensive Guide to CSS Pseudo-Classes and Their Usage appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/definite-guide-css-pseudoclasses/feed/ 12 26671
A Comprehensive Guide on Date Formatting for Global Websites https://www.hongkiat.com/blog/date-internationalization-api/ https://www.hongkiat.com/blog/date-internationalization-api/#comments Fri, 02 Feb 2024 10:00:36 +0000 https://www.hongkiat.com/blog/?p=23910 Mastering date formats is essential for websites with a global audience. Different regions prefer distinct date formats, and aligning with these preferences is key to user engagement and international success. This guide dives into the effective use of JavaScript’s Internationalization API, as defined by ECMA, for customizing date displays in various languages and cultural norms.…

The post A Comprehensive Guide on Date Formatting for Global Websites appeared first on Hongkiat.

]]>
Mastering date formats is essential for websites with a global audience. Different regions prefer distinct date formats, and aligning with these preferences is key to user engagement and international success. This guide dives into the effective use of JavaScript’s Internationalization API, as defined by ECMA, for customizing date displays in various languages and cultural norms. Learn how to handle different date formats, currencies, and time zones with ease.

Our focus: leveraging the Internationalization API for seamless and efficient date formatting across different languages and regions.

Display Date and Time: How to Do It Right

Display Date and Time: How to Do It Right

We come across them dates and time... well, every day. When it comes to the Web, you can... Read more

Determining the User’s Locale

To display the date in the user’s preferred local format, it’s important to first identify their locale. The most straightforward method is to allow users to choose their language and regional preferences on your webpage.

If direct user selection isn’t viable, other approaches include interpreting the Accept-Language header from user requests or utilizing the navigator.language (for Chrome and Firefox) or navigator.browserLanguage (for Internet Explorer) properties in JavaScript.

However, it’s important to note that these methods may not always accurately reflect the user’s browser UI language preference.

 var language_tag = window.navigator.browserLanguage || window.navigator.language || "en";
 // returns language tags like 'en-GB'
 

Verifying Internationalization API Support

To determine if a browser supports the Internationalization API, we can check for the presence of the global Intl object.

 if(window.hasOwnProperty("Intl") && typeof Intl === "object"){
 // The Internationalization API is available for use
 } 

Exploring the Intl Object

The Intl object in JavaScript serves as a gateway to the Internationalization API. It contains three constructor properties: Collator for string comparison, NumberFormat for number formatting, and DateTimeFormat for date and time formatting. Our focus will be on DateTimeFormat, which is instrumental in adapting date and time presentation to different languages.

Capabilities of the DateTimeFormat Object

The DateTimeFormat constructor in JavaScript takes two optional arguments:

  • locales – This can be a string or an array of strings indicating language tags, such as “de” for German or “en-GB” for English as used in the United Kingdom. In the absence of a specific language tag, the default locale of the runtime environment is used.
  • options – An object whose properties allow customization of the date formatter. It includes properties such as:
Property Description Possible values
day Day of the month “2-digit”, “numeric”
era Era in which the date falls, e.g., AD or BC “narrow”, “short”, “long”
formatMatcher Algorithm used for format matching “basic”, “best fit” [Default]
hour Hour of the day “2-digit”, “numeric”
hour12 Whether to use 12-hour format (true) or 24-hour format (false) true, false
localeMatcher Algorithm used for matching locales “lookup”, “best fit” [Default]
minute Minute of the hour “2-digit”, “numeric”
month Month of the year “2-digit”, “numeric”, “narrow”, “short”, “long”
second Second of the minute “2-digit”, “numeric”
timeZone Time zone to use for formatting “UTC”, default to the runtime’s time zone
timeZoneName Name of the time zone “short”, “long”
weekday Day of the week “narrow”, “short”, “long”
year Year “2-digit”, “numeric”

Example:

 var formatter = new Intl.DateTimeFormat('en-GB');
 // Returns a formatter for UK English date format
 var options = {weekday: 'short'};
 var formatter = new Intl.DateTimeFormat('en-GB', options);
 // Returns a formatter for UK English date format with weekday

Utilizing the format Function

The DateTimeFormat object includes a property accessor named format. This function is designed to format a Date object according to the specified locales and options within the DateTimeFormat instance.

It accepts either a Date object or undefined as an optional argument, returning a formatted date string.

Note: If no argument is provided, or if it’s undefined, the function defaults to formatting the current date using Date.now().

Here’s how it works:

 new Intl.DateTimeFormat().format()
 // Returns the current date in the format specific to the runtime's locale

Let’s explore some simple date formatting examples:

Now, let’s see how changing the language affects the output:

Next, let’s delve into the versatility of the formatting options:

Using the toLocaleDateString Method

As an alternative to the formatter approach, you can use Date.prototype.toLocaleDateString for similar functionality. This method also utilizes the locales and options arguments. While it’s similar to using the DateTimeFormat object, the latter is recommended for applications handling a large number of dates.

 var mydate = new Date('2015/04/22');
 var options = {
   weekday: "short", 
   year: "numeric", 
   month: "long", 
   day: "numeric"
 };

 console.log(mydate.toLocaleDateString('en-GB', options));
 // Outputs "Wed, 22 April 2015"

Checking Supported locales

To determine which locales are supported, the DateTimeFormat object’s supportedLocalesOf method can be used. This method returns an array of all supported locales or an empty array if none are supported. For example, to test, we can include a fictitious locale “blah” among the locales being checked.

 console.log(Intl.DateTimeFormat.supportedLocalesOf(["zh", "blah", "fa-pes"]));
 // Outputs Array [ "zh", "fa-pes" ]

References

The post A Comprehensive Guide on Date Formatting for Global Websites appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/date-internationalization-api/feed/ 5 23910
JavaScript Jargon: 10 Terms You Should Know https://www.hongkiat.com/blog/javascript-jargon/ https://www.hongkiat.com/blog/javascript-jargon/#comments Wed, 19 Jan 2022 13:01:43 +0000 https://www.hongkiat.com/blog/?p=24420 From currying to closures there are quite a number of JavaScript jargons (special words used within the field) knowing which will not only help you increase your vocabulary but understand JavaScript better. Jargons are normally found in documentations and technical articles. But some of them like closures are pretty standard things to know about. Knowing…

The post JavaScript Jargon: 10 Terms You Should Know appeared first on Hongkiat.

]]>
From currying to closures there are quite a number of JavaScript jargons (special words used within the field) knowing which will not only help you increase your vocabulary but understand JavaScript better.

Jargons are normally found in documentations and technical articles. But some of them like closures are pretty standard things to know about. Knowing what the word itself mean can help you know the concept it is named for better.

This post is the compilation of 10 such terms with their meaning and the context in which they are used in JavaScript. If you’re a beginner then this list has got you covered with the basics like hoisting. At the same time less-known or less-understood terms are also included in there.

  1. Arity
  2. Anonymous
  3. Closure
  4. Currying
  5. Hoisting
  6. Mutation
  7. Pragma
  8. Sentinel
  9. Vanilla
  10. Variadic
Learning JavaScript: Things to Know Before You Start

Learning JavaScript: Things to Know Before You Start

There is no doubt that JavaScript is an extensive programming language with plenty of helper libraries, frameworks, databases,... Read more

1. Arity

Arity (from Latin) is the term used to refer to the number of arguments or operands in a function or operation respectively. You’re most likely to come across this word in the realm of JavaScript when it is used to mention the number of arguments expected by a JavaScript function.

There is even a property named arity, of the Function object that returns the number of expected arguments in a function. It is now obsolete though and replaced by length.

The following function has an arity of 3.

function getName(first, middle, last){
 return first+' '+ middle +' '+last;
 }

2. Anonymous

Anonymous is an adjective. When something or someone is referred to as anonymous it means that thing’s or person’s name is unidentified. Likewise in JavaScript an anonymous function is the one that is not identified by a name.

(function (){
 //body
 })();

Above is an IIFE (Immediately Invoked Function Expression). The function in it is anonymous since it doesn’t have a name. Now, take a look at the one below.

var foo = function() {
 
 };

That is also said to be an anonymous function since there is no name after the key word function.

A little bit of doubt rises in the correctness of the use of the word “anonymous”. With IIFE, the function gets called right away, no name involved whereas, to call the latter function the syntax foo() is used.

It’s like we christened a nameless function with the name ‘foo’ and called it using that. Does that count as anonymous? I don’t know, I’ll leave that to the English experts. But, my confusion aside, they both are indeed referred to as anonymous function.

3. Closure

Here’s one of the definitions from oxford dictionary for closure: “A thing that closes or seals something, such as a cap or tie.”

In JavaScript, closure is an inner function, that is accessible outside of its outer function’s scope, with its connection to the outer function’s variables still intact.

To explain things (maybe not accurately but simply enough), consider closure as a waiter in a restaurant. A lot of things happen inside a restaurant kitchen, where we are not allowed to enter or see. But how are we supposed to get our food then?

That is where waiters come in. We call them, order the food, and then they’ll go to the kitchen, inform the chefs of the orders, and bring it to us when the order is ready. This way we’ve not broken any “rules” and can still manage to grab a meal.

The waiter is someone who is able to take our order into the kitchen and return with the food. JavaScript closures are similar to that, they are able to take our parameters and bring back us variables (references to those variables, to be precise) from inside a function that we aren’t allowed in.

function order() {
 var food; 
 function waiter(order) {
 chef(order);
 return food;
 }
 function chef(order) {
 if (order === 'pasta') {
 food = ['pasta', 'gravy', 'seasoning'];
 cook();
 }
 }
 function cook() { food.push('cooked'); }
 return waiter;
 }
 var myOrder = order();
 console.log(myOrder('pasta'));
 // Array [ "pasta", "gravy", "seasoning", "cooked" ]

As you can see from the above code, everything apart from waiter and its return value from inside the order function isn’t exposed to the outside world.

4. Currying

The effect, named after Haskell Curry, refers to using multiple functions with single arguments, in place of a single function with multiple arguments. Let’s see the add functions below for example.

function addx(x){
 function addy(y){
 return x+y;
 }
 return addy
 }
 
 function add(x,y){
 return(x+y);
 }
 
 console.log(addx(3)(4)); \\7
 console.log(add(3,4)); \\7

Both of the functions return the same result. The function addx accepts a parameter x while returning addy which in turn accepts the y value, performs the addition with x and returns the sum.

The function add simply takes both x and y at the same time, performs the addition and returns the sum. So far the first function might not seem very useful, until…

var add4 = addx(4);
 console.log(add4(8)); //12
 console.log(add4(6)); //10
 console.log(add4(-74)); //-70

Now, the former function suddenly gets interesting. In currying, you can always fix a step in a sequence of operations like the addition of 4 from the above code, which is helpful when one of the variables used in the operation is always the same.

5. Hoisting

Hoist means to raise something. Hoisting in JavaScript also means the same and what gets raised is the declaration (variable & function declarations).

Declarations are where variables and functions are created with keywords var(not for global) and function.

It doesn’t matter where you type the code to declare a function or variable, during evaluation all the declarations are moved up inside the scope where they reside (except for in strict mode). Hence, it is possible to write a working code with the code for function call placed before function declaration.

var name = 'Velma';
 console.log(sayCatchPhrase(name)); /"Jinkies!"
 
 function sayCatchPhrase(name) {
 phrases = {
 'Fred Flintstone': 'Yabba dabba doo!',
 'Velma': 'Jinkies!',
 'Razor': 'Bingo!',
 'He-Man': 'I Have the Power'
 };
 return phrases[name];
 }

6. Mutation

Mutation means change or modification. If you ever come across the word mutation in JavaScript it is probably referring to the changes that DOM elements went through.

There is even an API called MutationObserver to keep an eye out for the DOM mutations like addition of child elements or changes to the element’s attributes. (You can read more about MutationObserver in my post.)

7. Pragma

Pragma is short for pragmatic information. In plain English, pragmatic is an adjective that means sensible and practical. In programming, pragma refers to the code that consist of useful information on how a compiler or interpreter or assembler should process the program.

It does not contribute anything to the programming language itself and its syntax may vary. They only affect the compiler behavior. JavaScript also has few pragmas, one of them is strict.

"use strict";

By the above pragma, the JavaScript code will be executed in strict mode. In strict mode, bad syntax is not allowed, hoisting is not done, silent errors are shown, etc. It helps in writing a more secure and optimized JavaScript code.

8. Sentinel

Sentinels are soldiers who stand guard (Remember the ones from X-Men?). In programming, sentinels are values that are used to indicate the end of a loop or process. They can also be called “flags”.

You can use any reasonable value as a sentinel. Here’s an example of sentinels used in JavaScript; the indexOf method which returns -1 (the sentinel value) when the search value is not found in the targeted string. Below is a function that returns the position of an array value and if value is not found, returns -1.

function getPos(ary, val) {
 var i=0, len=ary.length; 
 for(;i<len;i++){
 if(ary[i]===val) return i+1;
 } 
 return -1;
 }
 console.log(getPos(['r','y','w'],'y')); //2
 console.log(getPos(['r','y','w'],'g')); //-1

9. Vanilla

I think everyone’s first ice cream flavor must’ve been vanilla. I also think that not only in ice cream, but in pretty much every sweet dish vanilla kind of became the standard flavor. I’ve seen quite a few cake recipes where they add at least one drop of it into the mix – just to increase the flavor.

And that’s what vanilla is, a traditional standard flavor. Vanilla JavaScript is referred to the standard JavaScript – no framework. Vanilla in fact is not only used to describe the standard version of JavaScript but also other languages like CSS.

10. Variadic

Variadic is an adjective created by joining “variable” and “adicity”. “Adicity” is from ancient Greek, with a meaning that is the same as the Latin word “arity” (Item 1 in this list). Thus, the term variadic is used to express something that has variable number of arguments.

In JavaScript, a variadic function takes in any number of arguments. It can be created using arguments property, apply method and since ES6, the spread operator. Below is an example using a spread operator.

function test(...a){
 console.log(a);
 }
 test('a','b','c',8,[56,-89]);
 //output is Array [ "a", "b", "c", 8, Array[2] ]

The post JavaScript Jargon: 10 Terms You Should Know appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/javascript-jargon/feed/ 10 24420
How to Download YouTube Videos Without Tools or Extensions https://www.hongkiat.com/blog/download-youtube-media-without-tools/ https://www.hongkiat.com/blog/download-youtube-media-without-tools/#comments Mon, 25 Oct 2021 13:01:42 +0000 https://www.hongkiat.com/blog/?p=25626 Downloading YouTube videos and audios is a fundamental chore for netizens. Sure, there are external tools out there to help you download youtube videos but if you are bothered by the incessant ads, and have concerns about malware, perhaps it’s time to start downloading YouTube media unaided. The catch is you’ll need a browser with…

The post How to Download YouTube Videos Without Tools or Extensions appeared first on Hongkiat.

]]>
Downloading YouTube videos and audios is a fundamental chore for netizens. Sure, there are external tools out there to help you download youtube videos but if you are bothered by the incessant ads, and have concerns about malware, perhaps it’s time to start downloading YouTube media unaided.

The catch is you’ll need a browser with a "Network" developer tool like modern IE or Chrome or Firefox, and an Internet connection setup where YouTube isn’t blocked (get some ideas on how to circumvent this block in this post).

My personal preference is Firefox, for reasons which will be clear at the end of this post but this works even if you prefer one of the other two browsers. Let’s check out the steps.

How to Download Instagram Videos (Tools and Tips)

How to Download Instagram Videos (Tools and Tips)

This post shows you how to download Instagram videos using PC tools, checking source codes, and using online... Read more

How to Download Youtube Media

1. Open Developer Tools in the browser and go to Network tool, or if you’re on Firefox press Ctrl + Shift + Q.

2. Click Media in the Network tool so that you’ll see only the HTTP requests made to media files, like audio and video files.

3. Browse to a YouTube video you want to download. You’ll start seeing the requests made by the YouTube page to the audio & video files in the Network tool.

4. Hover the cursor over the Type column of each request in the tool and look at the media type:

  • If you want the audio, look for "audio/mp4".
  • If you want the video, then look for "video/mp4".

Note: If you’re using a browser that doesn’t segeregate requests (like IE) or doesn’t list the requests made to the audio & video files in YouTube under "Media" (like Chrome), just search the term "audio" or "video" in the search bar in the Network tool.

5. Once you found a request with the wanted media type (it’ll be of the googlevideo.com domain), click on it, and copy the full URL from where it appears.

6. Paste the URL in the address bar, remove the range parameter in the query string and press Enter.

7. The video or audio will open, right-click on the page and select "Save As" to save the file.

8. If you want both the video and the audio, look for both with the steps above and put them together using any default media editor you have in your computer. It’s actually pretty easy and quick to do so (even with programs like the outmoded Windows Movie Maker).

yt-download-in-ff

Bonus: Tip for Firefox Users

If you’re getting WEBM audio files instead of MP4 from YouTube (webm can only be played in a browser) , disable your browser’s WEBM audio support, then YouTube will send the audio in MPEG4 format.

Type "about:config" in the address bar, press Enter, click through any warning message and search for "webm".

Find and double-click media.mediasource.webm.audio.enabled. Its value will change to false and you’re set.

webm firefox change

The post How to Download YouTube Videos Without Tools or Extensions appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/download-youtube-media-without-tools/feed/ 4 25626
Beginner’s Guide to Regular Expression (Regex) https://www.hongkiat.com/blog/getting-started-with-regex/ https://www.hongkiat.com/blog/getting-started-with-regex/#comments Fri, 14 May 2021 15:22:42 +0000 https://www.hongkiat.com/blog/?p=24068 A regular expression is a set of characters forming a pattern that can be searched in a string. Regex can be used for validation such as to validate credit card numbers, for search i.e. via complex text matches, and for replacing matched text with another string. It also has great multiple language support – learn…

The post Beginner’s Guide to Regular Expression (Regex) appeared first on Hongkiat.

]]>
A regular expression is a set of characters forming a pattern that can be searched in a string. Regex can be used for validation such as to validate credit card numbers, for search i.e. via complex text matches, and for replacing matched text with another string. It also has great multiple language support – learn it once and you can use it across many programming languages.

I've seen few people take the first look at regex, and ignore it completely. I don’t blame them; regex's syntax is complex and will make many cringes just like those command-line languages, only worse. But then every new thing is scary and seems impossible to learn at first. So, borrowing Horatius' words I'll say this; Begin, be bold, and venture to be wise.

30 Useful Regular Expressions Tools and Resources

30 Useful Regular Expressions Tools and Resources

Regular expression, or often known as regex, is a pattern that consist of rules used to match a... Read more

Regex – An Introduction

Regex had its roots in neuroscience and mathematics and was only implemented in programming in 1968 by Ken Thompson in QED text editor for text search. Now it's part of many programming languages like Perl, Java, Python, Ruby, and JavaScript.

Let’s look at some examples on how regex works.

I'll be using JavaScript in my examples. Now, to pass beginner level, you need to learn all the characters, classes, quantifiers, modifiers and methods used in regex. Here's a link to Mozilla Developer Network's Regular Expression page where you can view a table containing all those. You can also refer to the cheatsheet at the end of this post with most used characters.

Let’s see a simple example with an explanation. This is a regex.

regex

This is what the above regex will look for in a line, a character 'B' followed by at least one of any character between (and including) 'a' to 'z', 'A' to 'Z' and numbers 0 to 9.

Here's a sample of matches in a line highlighted:

Basket , bulb, B12 vitamin, BaSO4 , N BC company

The above regex will stop the search at Basket and return a positive response. That's because the global modifier 'g' has to be specified if you want the regex to look into all the possible matches.

Now, let's see how to use this expression in JavaScript. The test method goes: if found a match return true, else false.

 var input = "your test string", regex = /B[a-zA-Z\d]+/;
 if(!regex.test(input))
 alert('No match is found');
 else
 alert('A match is found');

Let's try another method: match returns the matches found in an array.

 var input = "your test string", 
 regex = /B[a-zA-Z\d]+/g, 
 /*I've added the global modifier 'g' to the regex to get all the matches*/
 ary = input.match(regex); 
 if(ary===null)
 alert('No match is found');
 else
 alert('matches are: ' + ary.toString());

How about string replace? Let's try that with regex now.

 var input = "your test string", 
 regex = /B[a-zA-Z\d]+/g;
 alert(input.replace(regex, "#"));

Below is a codepen for you to tweak. Click the "JavaScript" tab to view the JS code.

Regex Exercises

For exercises, you can google “regex exercises” and try solving them. Here’s what to expect when attempting these exercises, according to difficulty levels.

Basic

To me being able to validate a password is enough for starters. So, validate a password for 8 to 16 character length, alphanumeric with your choice of special characters allowed.

Intermediate

This is where you should practice with more real world data and learn few more regex points like lookahead, lookbehind assertions and matching groups;

  • Validate PIN codes, hexadecimals, dates, email ID, floating point.
  • Replace trailing zero, whitespaces, a set of matching words
  • Extract different parts of a URL
Advanced

You can optimize the above exercises' solutions – the most optimum regex for email has thousands of characters in it – so take it as far as you feel comfortable with and that's enough. You can also try:

  • Parsing HTML or XML (eventhough in the real world it is discouraged to do so because using regular expression to parse non-regular language like HTML will never make it foolproof. Plus XML parsing is a difficult task, more suitable for advanced level users)
  • Replacing tags
  • Removing comments (except the IE conditional comments)

Regex Tools

Tools to visualize regex are one of the coolest things out there for me. If you ever come across a long complex regex, just copy paste them into one of those tools and you'll be able to view the flow clearly. Besides that, there are many tools that you can use to fiddle with the regex code. They also showcase examples and cheatsheets along with share features.

  • Debuggex – It draws a regex diagram as per your input and you can make a quick share to StackOverflow right from there.
  • RegExr – You can test your regex with this one. It also got reference, a cheatsheet and examples to help you out.

Regex Cheatsheet

Token Definition
[abc] Any single character a, b or c
[^abc] Any character other than a, b or c
[a-z] Character between(including) a to z
[^a-z] Character except from a to z
[A-Z] Character between(including) A to Z
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit 0 to 9
\D Any non-digit
\w Any word character (letter, number & underscore)
\W Any non-word character
(…) Capture everything enclosed
(a|b) Match either a or b
a? Character a is either absent or present one time
a* Character a is either absent or present more times
a+ Character a is present one or more times
a{3} 3 occurences of character a consecutively
a{3,} 3 or more occurences of character a consecutively
a{3,6} 3 to 6 occurences of character a consecutively
^ Start of string
$ End of string
\b A word boundary. If a character is a word’s last or first word character or If a character is between a word or non-word character
\B Non-word boundary

The post Beginner’s Guide to Regular Expression (Regex) appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/getting-started-with-regex/feed/ 24 24068
10 Cool Things HTML Tags Can Do https://www.hongkiat.com/blog/cool-useful-html-tags/ https://www.hongkiat.com/blog/cool-useful-html-tags/#comments Thu, 29 Apr 2021 13:11:22 +0000 https://www.hongkiat.com/blog/?p=23967 At the moment there are a total of 142 HTML elements standardized by W3C excluding the ones in the initial phases of standardization and those that went obsolete. That said, it is possible to miss or forget few of them that can be useful when needed. Earlier we did a recap of some of the…

The post 10 Cool Things HTML Tags Can Do appeared first on Hongkiat.

]]>
At the moment there are a total of 142 HTML elements standardized by W3C excluding the ones in the initial phases of standardization and those that went obsolete. That said, it is possible to miss or forget few of them that can be useful when needed.

Earlier we did a recap of some of the best CSS tricks you might have overlooked. This post will remind you some of the HTML tags that you didn’t know you could use to implement features such as:

15 Beautiful Text Effects Created with CSS

15 Beautiful Text Effects Created with CSS

Beautiful text or typography will make your design look attractive. In web design, CSS helps to give style... Read more

1. Map Images

The HTML <map> elements can be used to create image maps. Image maps are basically images with clickable areas on them, that can be hyperlinked to another web page or other parts of the same document. You can define which areas of an image are clickable by simply mentioning the corresponding X Y coordinates of those points in the <area> elements nested inside <map>.

Note: The clickable areas cannot be styled through CSS so, if you want those markers to be styled, use a simple image editing software to draw the markers.

Tip: If you want to know the coordinates for a point in an image, open the image in an image editing software and move the cursor to that point, you should be able to see the coordinates of it in the software itself. For GIMP it is shown at left side of the bottom bar.

2. Input suggestions

Use <datalist> to provide a list of relevant suggestions that appear while typing an input value.

3. Highlight Text

Highlighted text usually has dark text color with a light background. You can achieve that highlighted text effect with markup alone. Any text enclosed inside the <mark> will have that effect.

You can customize the highlight color with the background-color CSS property of <mark> and the text color with the color property.

4. Define Templates

Along with HTML5 came the new <template> element. The <template> element holds markup inside it that is not rendered by the browsers, the markup enclosed by it are to be used to generate dynamic contents in the page using JavaScript.

For example, suppose you have a <table> where rows are to be added dynamically, you can simply put the markup of an empty row of that table inside the <template> tag and when needed call a JavaScript function containing script to copy the markup from inside the template tags and add it to the table markup. This is not supported by IE.

5. Fine Print

Fine print refers to the text of document that is typically printed in very small size containing information like conditions, terms, restrictions, citations, legal rights etc. The <small> tag in HTML can be used to show fine prints. From HTML5 onwards the <small> tag not only shows a fine-print styled text but will also semantically define the same as legal disclaimers and caveats.

6. Assign a Base URL

The <base>HTML element is quite handy when you have multiple links in your document with the same domain URLs, it allows you to add a base URL to the document which in turn allows you to add only relative URLs to other links in the page as needed.

Note: All of the relative URLs in the page will be referred based on the base URL, if you have any link with a different domain don’t forget to assign the complete URL to it.

7. Responsive Images

Responsive web development is in vogue with ever growing mobile access. Images can be toggled for different screen sizes with markup. The <picture> HTML5 element lets you add various image sources for different media for the image inside it.

Note: This currently works in Chrome only. You will have to set dom.image.picture.enable to true in about:config in Firefox.

8. Color Picker

HTML5 introduced many new input type elements; the color input element is one of them. It lets you chose a color on a webpage with the help of a color picker.

9. Group options

If you have many options in a dropdown list and would like to show them grouped, the <optgroup> element will get the job done. You can also style the groups with CSS.

10. The <noscript> element

The markup inside <noscript> is rendered by the browser only when the script is disabled. This tag is useful for letting users know when the script is disabled in their browser and to provide any alternate fallback mechanism for components on the web pages that will stop working without JavaScript.

 <head>
 <noscript><link rel="stylesheet" href="noscript_fallback.css"></noscript>
 </head>
 <body>
 <noscript><h2>Javascript is disabled in your browser.</h2></noscript>
 </body>
 

Now Read: 15 Useful CSS Tricks You Might Have Overlooked

The post 10 Cool Things HTML Tags Can Do appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/cool-useful-html-tags/feed/ 14 23967
The Greatest Inventions in Computer Programming https://www.hongkiat.com/blog/computer-programming-greatest-inventions/ https://www.hongkiat.com/blog/computer-programming-greatest-inventions/#comments Fri, 16 Apr 2021 15:33:39 +0000 https://www.hongkiat.com/blog/?p=24583 In one of the conversations I’ve had with our senior editor, I was asked the question, “How did the first programmers program?” This led to a discussion about Babbage and Ada Lovelace, at the end of which, I got assigned to research how it all began – it being the many firsts in computing history.…

The post The Greatest Inventions in Computer Programming appeared first on Hongkiat.

]]>
In one of the conversations I’ve had with our senior editor, I was asked the question, “How did the first programmers program?” This led to a discussion about Babbage and Ada Lovelace, at the end of which, I got assigned to research how it all began – it being the many firsts in computing history.

I dug into books and websites and was met with many revelations: Babbage isn’t technically the inventor of the computer, FORTRAN most definitely wasn’t the first high level programming language and we used to have styluses for CRT screens (really).

I was also surprised to find out how essential wars were in fueling the rapid progress of computer development, plus the contribution of many women that our textbooks chose to neglect. Hence, to fill the gaps in the history of computers and programs, I’ve put together 20 firsts in the world of computing, from bowling balls to WW2 and all that is in between.

1. First Computer: “Difference engine” (1821)

The “Difference Engine” was a proposed mechanical computer to be used to output mathematical tables.

Commissioned by the British government, Charles Babbage (aka Father of Computer) started working on it, but due to its high production cost, the funding was stopped and the machine was never completed.

differential engine

Image source: Wikimedia

2. First General Purpose Computer: “Analytical Engine” (1834)

The “Analytical Engine” was also a proposed mechanical computer, the input of which was supposed to be punched cards, with programs and data punched on them. Another brainchild of Charles Babbage, this machine was also not completed.

Analytical Engine

Image source: wikieducator.org

3. First Computer Program: algorithm to compute Bernoulli numbers (1841 – 1842)

Ada Lovelace (world’s first computer programmer) began translating Italian mathematician Luigi Menabrea’s records on Babbage’s analytical engine in 1841.

During the translation she became interested in the machine and left notes with her translation. One of the notes – note G, contained the algorithm to compute Bernoulli numbers by the analytical engine, considered to be the very first computer program.

first computer program

Image source: Wikimedia

4. First Working Programmable Computer: Z3 (1941)

Konrad Zuse (the Inventor of Computers) already had a working mechanical computer Z1 but it worked for only few minutes at a time.

The use of a different technology – relays, led to Z2 and eventually Z3. Z3 was an electromagnetic computer for which program and data were stored on external punched tapes. It was a secret project of the German government and put to use by The German Aircraft Research Institute.

The original machine was destroyed in the bombing of Berlin in 1943.

Z3 computer of Zuse

5. First Electronic Computer: Atanasoff-Berry Computer (ABC) (1942)

Created by John Vincent Atanasoff & Clifford Berry, the hence named Atanasoff-Berry Computer or ABC was used to find the solution for simultaneous linear equations.

It was the very first computer that used binary to represent data and electronic switches instead of mechanical. The computer however was not programmable.

Atanasoff-Berry Computer

Image source: galileog

6. First Programmable Electronic Computer: Colossus (1943)

The Colossus created by Tommy Flowers, was a machine created to help the British decrypt German messages that were encrypted by the Lorenz cipher, back in World War II.

It was programmed by electronic switches and plugs. Colossus brought the time to decipher the encrypted messages down from weeks to mere hours.

colossus computer

Image source: Wikimedia

7. First General Purpose Programmable Electronic Computer: ENIAC (1946)

Funded by the US Army, ENIAC or Electronic Numerical Integrator And Computer was developed in the Moore School of Electrical Engineering, University of Pennsylvania by by John Mauchly & J. Presper Eckert.

ENIAC was 150 feet wide and could be programmed to perform complex operations like loops; programming was done by altering its electronic switches and cables. It used card readers for input and card punches for output.

It helped with computations for feasibility of the world’s first hydrogen bomb.

ENIAC

Image source: hnf.de

8. First Trackball: (1946/1952)

Why the two years for the first trackball? Allow me to explain.

The first year was the year given by a Ralph Benjamin, who claimed to have created the world’s first trackball back when he was working on a monitoring system for low-flying aircraft in 1946. The invention he described used a ball to control the X-Y coordinates of a cursor on screen.

The design was patented in 1947 but was never released because it’s considered a “military secret”. The military opted for the joystick instead.

The second contender for world’s first trackball, used in the Canadian Navy’s DATAR system back in 1952 was invented by Tom Cranston and co. This trackball design had a mock up which utilized a Canadian bowling ball spun on “air bearings” (see image below).

datar trackball

Image source: engadget

9. First Stored-Program Computer: SSEM (1948)

To overcome the shortcomings of delay-line memory, Frederic C. Williams and Tom Kilburn had developed the first random-access digital storage device based on the standard CRT.

The SSEM (Manchester Small-Scale Experimental Machine) was used to implement that storage device for practical usage. The programs were entered in binary form using 32 switches and its output was a CRT.

Replica of the SSEM

Image source: The Staffordshire University Computing

10. First High-Level Programming Language: Plankalkül (1948)

Although Konrad Zuse started working on Plankalkül since 1943, it was only in 1948 when he published a paper about it. It did not attract much attention unfortunately. It would take close to three decades later for a compiler to be implemented for it, one created by a Joachim Hohmann in a dissertation.

The Plankalkül , Chapter 5 , Chess Theory

11. First Assembler: “Initial Orders” for EDSAC (1949)

Assembler is a program that converts mnemonics (low-level) into numeric representation (machine code). The initial orders in EDSAC (Electronic Delay Storage Automatic Calculator) was the first of such a system.

It was used to assemble programs from paper tape input into the memory and running the input. The programs were in mnemonic codes instead of machine codes, making “initial code” the first ever assembler by processing a symbolic low level program code into machine code.

Initial Order

Image source: Cambridge University Computer Lab

12. First Personal Computer: “Simon” (1950)

“Simon” by Edmund Berkeley was the first affordable digital computer that could perform four operations: addition, negation, greater than, and selection. The input was punched paper, and the program ran on paper tape. The only output were through five lights.

Simon Computer Edmund Berkeley

13. First Compiler: A-0 for UNIVAC 1 (1952)

A compiler is a program that converts high-level language into machine code. The A-0 System was a program created by the legendary Grace Hopper to convert a program specified as a sequence of subroutines and arguments into machine code.

The A-0 later evolved into A-2 and was released to customers with its source code making it possibly the very first open source software.

Grace_Hopper_and_UNIVAC

Image source: Wikimedia

14. First Autocode: Glennie’s Autocode (1952)

An Autocode is a high-level programming language that uses a compiler. The first autocode and its compiler appeared at the University of Manchester to make the programming of the Mark 1 machine more intelligible.

It was created by Alick Glennie, hence the name Glennie’s Autocode.

glennie autocode

Image source: Wikipedia

15. First Real-Time Graphics Display Computer: AN/FSQ-7 by IBM (1951)

AN/FSQ-7 was based on one of the first computers that showed real-time output, Whirlwind. It became the lifeline for the US Air Defense system known as Semi-Automatic Ground Environment (SAGE).

The computers showed tracks for the targets and automatically showed which defences were within range. AN/FSQ-7 had 100 system consoles; here’s one (image below), the OA-1008 Situation Display (SD), with a light gun used to select targets on screen for further information.

an-fsq-7

Image source: Wikiwand

16. First Widely Used High Level Programming Language: FORTRAN (1957)

If you check the textbooks, you will find FORTRAN listed as the first high level programming language.

Thought up by John W. Backus who disliked writing programs and decided to create a programming system to help make the process much easier, the use of FORTRAN greatly reduced the number of programming statements required to get a machine running.

By 1963, more than 40 FORTRAN compilers were already available.

fortran-punch-card

Image source: Wikipedia

17. First Mouse (1964)

It was while sitting in a conference session on computer graphics that the idea of a mouse came to Douglas Engelbart in 1964.

He thought up a device with a pair of small wheels (one turns horizontally the other vertically) which can be used to move a cursor on a screen. A prototype (see below) was created by his lead engineer, Bill English but both English and Engelbart never received royalties for the design because technically, it belonged to SRI, Engelbert’s employer.

First mouse prototype

Image source: Michael Hicks

18. First Commercial Desktop Computer: Programma 101 (1965)

Also known as Perottina, Programma 101 was the world’s first commercial PC. It could perform addition, subtraction, multiplication, division, square root, absolute value, and fraction.

For all that it could do, it was priced at $3,200 (it was a very different time) and managed to sell 44,000 units. Perottina was invented by Pier Giorgio Perotto and produced by Olivetti, an Italian manufacturer.

programma-101

Image source: TEDxArezzo

19. First Touchscreen (1965)

It doesn’t look like much but this was the first touchscreen the world has ever known. It’s a capacitative touchscreen panel, with no pressure sensitivity (there’s either contact, or no contact) and it only registers a single point of contact (as opposed to multitouch).

The concept was adopted for use by air traffic controllers in the UK up until the 1990s.

touchscreen Johnson

Image source: arstechnica

20. First Object Oriented Programming Language: Simula (1967)

Based on C. A. R. Hoare’s concept of class constructs, Ole-Johan Dahl & Kristen Nygaard updated their “SIMULA I” programming language with objects, classes and subclasses. This resulted in the creation of SIMULA 67 which became the first object-oriented programming language.

Simula sample program

Image source: Wikipedia

Final thoughts

As much as this post was about what we could learn about the many firsts in computing history it is hard to immerse ourselves in history itself. As a result, at least for me, we become more appreciative about the work done by generations before ours, and we can better understand what drives the many changes that shape the world that we live in today.

I hope this post inspires you as much as it inspired me. Share your thoughts on these firsts, and if I missed any, which I’m sure I did, do add them in the comments.

Now Read: 40 People Who Changed the Internet

The post The Greatest Inventions in Computer Programming appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/computer-programming-greatest-inventions/feed/ 6 24583
CSS Floats Explained in Five Questions https://www.hongkiat.com/blog/css-floats/ https://www.hongkiat.com/blog/css-floats/#comments Tue, 16 Jun 2020 13:13:25 +0000 https://www.hongkiat.com/blog/?p=24905 CSS "Floats" (floating elements) are simple to use but once used, the effect it has on the elements around it sometimes get unpredictable. If you have ever come across the problems of vanishing nearby elements or floats that poke out like a sore thumb, worry no more. This post covers five basic questions that will…

The post CSS Floats Explained in Five Questions appeared first on Hongkiat.

]]>
CSS "Floats" (floating elements) are simple to use but once used, the effect it has on the elements around it sometimes get unpredictable. If you have ever come across the problems of vanishing nearby elements or floats that poke out like a sore thumb, worry no more.

This post covers five basic questions that will help you become an expert at floating elements.

  1. Which elements don’t float?
  2. What happens to an element when it floats?
  3. What happens to the siblings of "Floats"?
  4. What happens to a parent of a "Float"?
  5. How do you clear "Floats"?

For readers who addopt the TL;dr approach to life, there’s a summary near the end of the post.

1. Which elements don’t float?

An absolute or fixed positioned element won’t float. So the next time you encounter a float that isn’t working, check if it is in position:absolute or position:fixed and apply changes accordingly.

2. What happens to an element when it floats?

When an element is tagged "float" it runs to either the left or the right basically until it hits the wall of its container element. Alternatively, it will run until it hits another floating element that has already hit the same wall. They’ll keep piling up side by side until the space runs out, and newer incoming ones will be moved down.

Floating elements also won’t go above the elements before it in the code, something you need to consider before coding a “Float” after an element to the side of which you want to float it.

float below others

Here are two more things that happen to a floating element depending on what type of element is being kept floating:

An inline element will turn into a block-level element when floated

Ever wondered why suddenly you’re able to assign height & width to a floating span? That’s because all the elements when floated will get the value block for its display attribute (inline-table will get table) making them block level elements.

floating span
A block element of unspecified width will shrink to fit its content when floated

Usually, when you don’t specify width to a block element, its width is the default 100%. But when floated, that’s no more the case; the block element’s box will shrink until its contents remain visible.

floating div

3. What happens to The Siblings of "Floats"?

When you decide to float an element among a bunch of elements don’t worry about how it’s going to behave, its behavior will be predictable and will either move left or right. What you should really be thinking about is how the siblings after it are going to behave.

"Floats" have the most caring and obedient later siblings in the entire world. They’ll do everything in their power to accommodate a floating element.

The text and inline elements will simply make way for the "Floats" and will surround the "Float" when it’s in position.

The block elements will go a step further and will wrap themselves around a "Float" generously, even if it means kicking out their own child elements to make space for the "Float".

Let’s check this out in an experiment. Below are a blue box and after it is a red box of the same size with some child elements.

Now, let’s float the blue box, and see what happens to the red box and its children.

Everything will be fine once the red box stops embracing the blue box and for that you can use overflow:hidden.

When you add overflow:hidden to an element that has been wrapping a float, it’ll stop doing so. See below how the red box behaves with overflow:hidden.

4. What happens to a parent of a "Float"?

Parents don’t care much about their "Float" children, except that they shouldn’t go out of their left or right boundaries.

Typically a block element of unspecified height increases its height to accommodate its child elements, but that isn’t the case for "Float" children. If a "Float’s" size increases, its parent won’t increase its height accordingly. This again can be solved by using overflow:hidden in the parent.

5. How to clear "Floats"?

I’ve already mentioned using overflow:hidden to make a parent height-wise accommodate a floating child while creating the right space for other elements after the "Float" and to stop siblings from wrapping "Floats.

And that’s how you make an element live near a "Float" with no compromises.

There’s another method where the elements won’t even be anywhere near their "Float" siblings. By using the clear attribute you can make an element free from being near a "Float".

clear: left; 
clear: right;
clear: both;

left value clears all "Floats" to the left of the element, and vice versa for right, and on both sides for both. This clear attribute can be used on a sibling, empty div or on pseudo element as per your convenient.

Summary

  1. Absolute/Fixed elements won’t float.
  2. A "Float" doesn’t go above the element before it in the code.
  3. If there is not enough space in the container, a "Float" will be pushed down.
  4. All "Floats" are made into block-level elements.
  5. If width is not specified on a "Float", it’ll shrink to fit the content.
  6. The later siblings of a "Float" will either surround them (inline & text) or wrap them (blocks).
  7. To stop an element from wrapping a "Float", use overflow:hidden.
  8. The parents of a "Float"s would not increase its height to fit the float.
  9. To make a parent increase its height as per the "Float", use overflow:hidden (or create an empty sibling with clear after it).
  10. To prevent an element being near any "Float" use the clear attribute.

The post CSS Floats Explained in Five Questions appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/css-floats/feed/ 7 24905
How to Stream Truncated Audio Using MediaSource API https://www.hongkiat.com/blog/mediasource-api-stream-truncated-audio/ https://www.hongkiat.com/blog/mediasource-api-stream-truncated-audio/#comments Fri, 05 Jun 2020 13:11:10 +0000 https://www.hongkiat.com/blog/?p=29581 With the MediaSource API, you can generate and configure media streams right in the browser. It allows you to perform a variety of operations on media data held by media-related HTML tags such as <audio> or <video>. For instance, you can mix different streams, create overlapping media, lazy load media, and edit media metrics such…

The post How to Stream Truncated Audio Using MediaSource API appeared first on Hongkiat.

]]>
With the MediaSource API, you can generate and configure media streams right in the browser. It allows you to perform a variety of operations on media data held by media-related HTML tags such as <audio> or <video>. For instance, you can mix different streams, create overlapping media, lazy load media, and edit media metrics such as change the volume or the frequency.

In this post, we’ll specifically see how to stream an audio sample (a truncated MP3 file) with the MediaSource API right in the browser in order to pre-show music to your audience. We will cover how to detect support for the API, how to connect the HTML media element to the API, how to fetch the media via Ajax, and finally how to stream it.

How to Display Timed Transcript Alongside Played Audio

How to Display Timed Transcript Alongside Played Audio

Audio transcript is the text version of speech, helpful in providing useful materials like recorded lectures, seminars, etc.... Read more

If you want to see in advance what we are up to, have a look at the source code on Github, or check out the demo page.

MediaSource API

Step 1 – Create the HTML

To create the HTML, add an <audio> tag with a controls attribute to your page. For backward compatibility, also add a default error message for users whose browsers don’t support the feature. We will use JavaScript to turn on/off this message.

<audio controls>
Your browser doesn't support HTML audio element.
</audio>

Step 2 – Detect browser support

In JavaScript, create a try…catch block that will throw an error if the MediaSource API is not supported by the user’s browser, or, with other words if MediaSource (the key) does not exist in the window object.

try {
  if (!'MediaSource' in window)
    throw new ReferenceError('There is no MediaSource property
          in window object.')
  } catch (e) {
    console.log(e);
}

Step 3 – Detect MIME support

After the support check, also check for the support of the MIME type. If the MIME type of the media you want to stream is not supported by the browser, alert the user and throw an error.

var mime = 'audio/mpeg';
if (!MediaSource.isTypeSupported(mime)) {
  alert('Can not play the media. Media of MIME type ' +
        mime + ' is not supported.');
  throw ('Media of type ' + mime +
        ' is not supported.');
}

Note that the code snippet above needs to be placed inside the try block, before the catch block (for reference, follow the line numbering or check out the final JS file on Github).

Step 4 – Link the <audio> tag to the MediaSource API

Create a new MediaSource object, and assign it as the source of the <audio> tag by using the URL.createObjectURL() method.

var audio = document.querySelector('audio'),
mediaSource = new MediaSource();
audio.src = URL.createObjectURL(mediaSource);

Step 5 – Add a SourceBuffer object to MediaSource

When a HTML media element accesses a media source and is ready to create SourceBuffer objects, the MediaSource API fires a sourceopen event .

The SourceBuffer object holds a chunk of media that is eventually decoded, processed and played. A single MediaSource object can have multiple SourceBuffer objects.

Inside the event handler of the sourceopen event, add a SourceBuffer object to MediaSource with the addSourceBuffer() method.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
});

Step 6 – Fetch the media

Now that you have a SourceBuffer object, it’s time to fetch the MP3 file. In our example, we’ll do so by using an AJAX request.

Use arraybuffer as responseType, which denotes binary data. When the response is successfully fetched, append it to SourceBuffer with the appendBuffer() method.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  var xhr = new XMLHttpRequest;
  xhr.open('GET', 'sample.mp3');
  xhr.responseType = 'arraybuffer';
  xhr.onload = function() {
      try {
          switch (this.status) {
              case 200:
                sourceBuffer.appendBuffer(this.response);
                break;
              case 404:
                throw 'File Not Found';
              default:
                throw 'Failed to fetch the file';
         }
      } catch (e) {
        console.error(e);
      }
    };
    xhr.send();
});

Step 7 – Indicate the end of the stream

When the API has finished appending the data to SourceBuffer an event called updatend is fired. Inside an event handler, call the endOfStream() method of MediaSource to indicate that the stream has ended.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  var xhr = new XMLHttpRequest;
  xhr.open('GET', 'sample.mp3');
  xhr.responseType = 'arraybuffer';
  xhr.onload = function() {
    try {
      switch (this.status) {
        case 200:
            sourceBuffer.appendBuffer(this.response);
            sourceBuffer.addEventListener('updateend', function (_){
                mediaSource.endOfStream();
            });
            break;
        case 404:
            throw 'File Not Found';
        default:
            throw 'Failed to fetch the file';
      }
    } catch (e) {
      console.error(e);
    }
  };
  xhr.send();
});

Step 8 – Truncate the media file

The SourceBuffer object has two properties called appendWindowStart and appendWindowEnd representing the start and end time of the media data you want to filter. The highlighted code below filters the first four seconds of the MP3.

mediaSource.addEventListener('sourceopen', function() {
  var sourceBuffer = this.addSourceBuffer(mime);
  sourceBuffer.appendWindowEnd = 4.0;
  ...
});

Demo

And that’s all, our audio sample is streamed right from the web page. For the source code, have a look at our Github repo and for the final result, check out the demo page.

Browser support

As of writing this post, the MediaSource API is officially supported in all major browsers. But the testing shows that the implementation is buggy in Firefox, and Webkit browsers still have troubles with the appendWindowStart property.

As the MediaSource API is still in its experimental stage, access to higher editing functions may be limited but the basic streaming feature is something you can make use of right away.

The post How to Stream Truncated Audio Using MediaSource API appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/mediasource-api-stream-truncated-audio/feed/ 2 29581
15 Useful Slack Tips You Should Know https://www.hongkiat.com/blog/slack-tips/ https://www.hongkiat.com/blog/slack-tips/#comments Tue, 05 May 2020 13:42:13 +0000 https://www.hongkiat.com/blog/?p=29532 Slack‘s simplicity and versatility quickly made it one of the most powerful productivity tools of our days, on which many teams rely in their day-to-day communication. However, in spite of its uncomplicated UI, we can still miss some of its useful and even quirky settings—at least if we don’t look at the right places. So,…

The post 15 Useful Slack Tips You Should Know appeared first on Hongkiat.

]]>
Slack‘s simplicity and versatility quickly made it one of the most powerful productivity tools of our days, on which many teams rely in their day-to-day communication. However, in spite of its uncomplicated UI, we can still miss some of its useful and even quirky settings—at least if we don’t look at the right places.

So, in this article, we cover 15 useful tips to track these settings down and help you improve your productivity while working with Slack.

10 Useful Slack Tools For Better Productivity

10 Useful Slack Tools For Better Productivity

Since its launch in 2013, Slack has grown to become a top team communication tool to generate conversations,... Read more

1. Browse messages by date

Slack allows you to browse messages by date in any channels. To do so, select on the “More” icon, designated with three dots icon at the sidebar of the channel. Click on the “Jump to date”, as seen below.

Slack customize slack

This will launch the the Slack’s calendar where you can freely browse and jump on the previous conversations at any dates, months, or years. Just keep in mind that this may work better if your Workspace is on one of the Slack’s paid plan. The Slack free-tier plan limits the number of previous conversations that you can see.

Slack Message Archive

2. Share a file to public

To share a file uploaded to Slack to public, hover over that file, click on the three dots menu that appears on the right, and select the Create external link… option from the action menu.

Slack external link

3. Switch to compact view

If you receive a lot of messages in Slack and would like to see as many messages as you can without scrolling opt for the compact view. User profile pictures are hidden in compact view, which allows you to save a fair amount of space.

Click on your username in the top-left corner. In the dropdown menu, click Preferences, then select Messages & Media. In the Message Display > Message Theme section, select Compact to enable the compact view.

Slack compact view

4. Add the shrugging ASCII emoji

There are just too many times when you want to let your team know that well… you have just shrugged your shoulders. Slack makes it possible to quickly add the shrugging ASCII emoji (looks like this: ¯\_(ツ)_/¯) to a message. Just enter the /shrug slash command into the message input bar.

Slack shrug

5. Stay organised with channel prefix

Conversations in Slack happen in Channels. Creating these channels using a clear predictable naming structure will allow you to ensure your workspace is organized and help people to ask questions in the right place, find information quickly, and work efficiently. By default, Slacks already created 3 default prefix, namely:

  • help — For questions, assistance, and resources on a topic
  • proj — For collaboration on and discussion about a project
  • team — For updates and work from a department or team

You can also create one or remove these default Channel prefix to meet the need of your orgaisation. To do so, go to the Workspace settings in this URL https://[name].slack.com/customize/channels, with [name] being the Workspace name. This URL can also be accessed from the Slack menu at Settings & administration > Workspace settings.

Within the settings page, go to the Channel Prefix section and click the “Add Prefix” button to add a new one.

Slack default channel prefixes
Slack default channel prefixes

6. Assign a reminder to a message

If you get a message but want to reply only later, you can add a reminder to it. To assign a reminder to a message, take the cursor over it and click on the three dots menu to trigger the action menu. Here, hover over Remind me about this and select a delay time.

Slack reminder

After choosing a time, you’ll immediately see an acknowledgement of the reminder in the messages window.

7. Add custom and special emojis

Slack lets you add your custom emojis. To do so, click on the top-left menu, and select Customize Slack. It opens the aforementioned customization page in the browser. In the Emoji tab, you can choose a name for your custom emoji, and upload and save the emoji image.

You can also directly go to the [myteam].slack.com/customize/emoji URL.

Slack custom emoji

Slack also has a set of its own in-house custom emojis. They are not available from the customization page but from the message bar inside the Slack app. Open the emoji input box on the right side of the message bar, then click on the Slack icon to see the custom emojis.

Slack in-house emojis

8. Assign colors to users in compact mode

In compact mode, you can assign a color in which the username of a certain user will be displayed. To do so, enter the /color @username FFFFFF command into the message bar.

For instance, to change the color of the “johndoe” username to red, you need to enter the /color @johndoe ff0000 command. The color value uses hex codes.

Slack username color

9. Stay alert with highlighted words

Sometimes you want to get notified when someone mentioned specific phrases or words that matters to you. For example, you want to be notified when someone’s mentioned your name, your secret project code, area of interest, or any other conversation you want to stay in the loop.

To set up these keywords, you can go to the “Preference” menu from the top-left of the Slack window. Then go to the “Notifications” section and add the words or phrases on the “My Keywords” section as seen below.

Slack higlight words

10. Syntax highlight code snippets

You can message a code block in Slack by enclosing the code with ```, but if the code block is quite big, I recommend you to use code snippets instead of code blocks. Code snippets are syntax highlighted code or text files that can be commented and downloaded by the receiver.

To create a new code snippet, click on the plus sign shown on the left of the message bar, select Code or text snippet, and create your snippet.

Slack code snippet menu
Slack code snippet popup
Slack code snippet added

11. Remove text previews

Slack shows text previews of links by default in the Messages window. These previews can be useful, but if your team shares many links they may take up quite a few place.

You can disable the preview feature from the aforementioned Preferences > Messages & Media settings page. You need to uncheck the Show text previews of linked websites option in the Inline Media & Links section.

Slack text preview

12. View keyboard shortcuts

You can quickly have a look at the list of key bindings available in Slack by pressing Ctrl + / on Windows, or Cmd + / on Mac.

13. Configure the notification sound

Slack has some options to configure the notification sound. The options can be accessed from the Preferences menu, under the Notification Settings > Sounds section.

Slack notification sounds

14. View team stats

You can view your team’s statistics on the [yourteam].slack.com/stats web page. Other than typing the URL into the address bar of your browser, you can also reach it from the Slack app by selecting the Statistics option in the top-left menu.

The stats page shows a set of metrics including total messages in the team account, number of readers, number of posters, and files created.

Slack stats

15. Assign a default skin tone to emojis

You can make your emojis have a default skin tone. To do so, access the Emoji popup box by clicking on the Emoji icon on the right of the message bar.

Here, click on the Skin Tone option displayed in the bottom-right corner, and select the one you want to set as the default skin tone for your emojis.

Slack emoji skin

The post 15 Useful Slack Tips You Should Know appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/slack-tips/feed/ 2 29532
How to Send Customized Messages to Slack From your App https://www.hongkiat.com/blog/send-messages-to-slack/ https://www.hongkiat.com/blog/send-messages-to-slack/#comments Mon, 20 Jan 2020 15:43:44 +0000 https://www.hongkiat.com/blog/?p=25507 Slack is a popular messaging app used by many teams. It comes with a lot of services and an API for developers to integrate it with their applications. In today’s post we’ll see how to use one of its services called Incoming Webhooks, to send data to slack from an external application. This way we…

The post How to Send Customized Messages to Slack From your App appeared first on Hongkiat.

]]>
Slack is a popular messaging app used by many teams. It comes with a lot of services and an API for developers to integrate it with their applications. In today’s post we’ll see how to use one of its services called Incoming Webhooks, to send data to slack from an external application.

This way we can easily send messages to Slack from any application we already have; we can send reports, updates, news, notifications and more. For this post, I’ve used JavaScript in the example. To begin, sign into your team’s Slack account.

10 Useful Slack Tools For Better Productivity

10 Useful Slack Tools For Better Productivity

Since its launch in 2013, Slack has grown to become a top team communication tool to generate conversations,... Read more

1. Set up the Integration

You’ll first have to set up an incoming webhook integration. Go to yourteam.slack.com/apps/build/custom-integration and click on Incoming Webhooks, then select a channel or user you want to post your messages to (this selection can be overridden later in code).

Once done, you’ll see your incoming webhook integration’s configuration page.

Scroll down and there’ll be a Webhook URL in the format https://hooks.slack.com/services/TXXXXXXXX/BXXXXXXXX/token. Save that URL somewhere, we’ll need it later. You can further change the icon and name of the integration in this page itself, but we’ll do that in code.

2. Create the Message

Let’s imagine you’ve already created a web app that seeks out Valentine’s Day sales in popular sites as well as the offer codes for use during the sale, and for some reason, you want to share this result with your Slack team members.

All we have to do now is to use the webhook URL created in the previous step and post a request to it from your application with JSON data, which will concoct the sale offer message.

Let’s first put together the JSON string that’ll be turned into the Slack message. The parameter carrying the JSON data is called payload, hence the JSON string should look like this:

var myJSONStr = 'payload= {"username": "SALE BOT", "icon_url": "example.com/img/icon.jpg", "channel": "#general"}'

icon_url is the URL to the image that’ll show up as the profile picture, you can also use icon_emoji to display an emoji as the profile picture instead, for example "icon_emoji": ":gift:". "channel" specifies the channel or username who’ll see your message. For username use the syntax "@username", for channel "#channelname".

Now for the actual message; you can either add the "text" property and write your message as its value and be done with it, or use the property called "attachment" to add richly formatted text, which is what we’ll be doing now.

The "attachment" property of payload goes like this:

"attachments": [{
    "fallback": "The attachement isn't supported.",
    "title": "VALENTINE'S DAY OFFER",
    "color": "#9C1A22",
    "pretext": "Today's list of awesome offers picked for you",
    "author_name": "Preethi",
    "author_link": "https://www.hongkiat.com/blog/author/preethi/",
    "author_icon": "https://assets.hongkiat.com/uploads/author/preethi.jpg",
    "mrkdwn_in": ["text","fields"],
    "text": "Just click the site names and start buying. Get *extra reduction with the offer code*, if provided.",
    "thumb_url": "http://example.com/thumbnail.jpg"
}]

"fallback" is the alternative text to be shown when the Slack message is viewed in an application that doesn’t support message attachment (like in mobile notifications).

"color" is the left border color of the message.

"pretext" is the text that’s shown before the main content.

"author_link" is the URL hyperlinked in author’s name (if provided).

"mrkdwn_in" is an array of property names whose values are shown formatted in the message — based on markdown syntax like (*) for bold and (_) for italics. The three possible values for "mrkdwn_in" are "text", "pretext" and "fields"

"thumb_url" is the thumbnail image’s URL.

Here’s how the message will look like so far.

Now let’s add the fields to the attachment array, which will display the sites and offer codes in two columns.

"fields": [{
    "title": "Sites", 
    "value": "_<https://www.amazon.com/|Amazon>_\n_<http://www.ebay.com|Ebay>_",
    "short": true
}, {
    "title": "Offer Code",
    "value": "UI90O22\n-",
    "short": true
}],

Use \n to add line break and the syntax <link|link name> to add hyperlinks.

Underscore is used to format text in italics.

short is set to true if the values are to be displayed side by side (like if it’s short). Put together, the JSONString will look like this (keep the string in a single line in actual working code)

var myJSONStr = 'payload= {
    "username": "SALE BOT",
    "icon_url": "example.com/img/icon.jpg",
    "attachments": [{
        "fallback": "This attachement isn't supported.",
        "title": "VALENTINE'S DAY OFFER",
        "color": "#9C1A22",
        "pretext": "Today's list of awesome offers picked for you",
        "author_name": "Preethi",
        "author_link": "https://www.hongkiat.com/blog/author/preethi/",
        "author_icon": "https://assets.hongkiat.com/uploads/author/preethi.jpg",
        "fields": [{
            "title": "Sites",
            "value": "_<https://www.amazon.com/|Amazon>_\n_<http://www.ebay.com|Ebay>_",
            "short": true
        }, {
            "title": "Offer Code",
            "value": "UI90O22\n-",
            "short": true
        }],
        "mrkdwn_in": ["text", "fields"],
        "text": "Just click the site names and start buying. Get *extra reduction with the offer code*, if provided.",
        "thumb_url": "http://example.com/thumbnail.jpg"
    }]
}';

3. Post the Request

Now to make the post request in JavaScript, use the function below:

function postMessageToSlack(){
    var xmlhttp = new XMLHttpRequest(),
        webhook_url = url-you-saved-from-before,
        myJSONStr= json-string-from-above;
    xmlhttp.open('POST', webhook_url, false);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(myJSONStr);
}

Add this function to a button click or page load to see it working.

The final output will look something like this:

incoming webhook

The post How to Send Customized Messages to Slack From your App appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/send-messages-to-slack/feed/ 4 25507
How to Create an Animated Favicon Loader with JavaScript https://www.hongkiat.com/blog/animated-favicon-loader-javascript/ https://www.hongkiat.com/blog/animated-favicon-loader-javascript/#comments Sat, 11 Jan 2020 15:25:20 +0000 https://www.hongkiat.com/blog/?p=28847 Favicons are a crucial part of online branding, they give a visual cue to users, and help them distinguish your site from others. Although most favicons are static, it is possible to create animated favicons as well. A constantly moving favicon is certainly annoying for most users, and also harms accessibility, however when it’s only…

The post How to Create an Animated Favicon Loader with JavaScript appeared first on Hongkiat.

]]>
Favicons are a crucial part of online branding, they give a visual cue to users, and help them distinguish your site from others. Although most favicons are static, it is possible to create animated favicons as well.

A constantly moving favicon is certainly annoying for most users, and also harms accessibility, however when it’s only animated for a short time in response to a user action or a background event, such as a page load, it can provide extra visual information—therefore improving user experience.

Let’s Talk About the Importance of Favicons

Let’s Talk About the Importance of Favicons

Discover the importance of favicons for your website and learn how to create and implement them. Improve your... Read more

In this post, I’ll show you how to create an animated circular loader in a HTML canvas, and how you can use it as a favicon. An animated favicon loader is a great tool to visualize the progress of any action performed on a page, such as file uploading or image processing. You can have a look at the demo belonging to this tutorial on Github as well.

Canvas Loader Gif Demo

1. Create the <canvas> element

First, we need to create a canvas animation that draws a full circle, 100 percent in total (this will be important when we need to increment the arc).

<button id=lbtn>Load</button>
<canvas id=cvl width=16 height=16></canvas>

I’m using the standard favicon size, 16*16 pixels, for the canvas. You can use a size bigger than that if you want, but note that the canvas image will be scaled down to the 162 pixel area when it’s applied as a favicon.

2. Check if <canvas> is supported

Inside the onload() event handler, we get a reference for the canvas element [cv] using the querySelector() method, and refer its 2D drawing context object [ctx] with the help of the getContext() method.

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        /* ... */
    }
};

We also need to check if the canvas is supported by the UA by making sure that the drawing context object [ctx] exists and isn’t undefined. We’ll place all the code belonging to the load event into this if condition.

Master DOM Manipulation with 15 Essential JavaScript Methods

Master DOM Manipulation with 15 Essential JavaScript Methods

As a web developer, you frequently need to manipulate the DOM, the object model that is used by... Read more

3. Create the initial variables

Let’s create three more global variables, s for the starting angle of the arc, tc for the id for the setInterval() timer, and pct for the percentage value of the same timer. The code tc = pct = 0 assigns 0 as the initial value for the tc and pct variables.

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        s = 1.5 * Math.PI,
        tc = pct = 0;
    }
};

To show how the value of s was calculated, let me quickly explain how arc angles work.

Arc angles

The subtended angle (the angle composed of the two rays that define an arc) of the circumference of a circle is 2π rad, where rad is the radian unit symbol. This makes the angle for a quarter arc equal to 0.5π rad.

subtended angle of circumference

When visualizing the loading progress, we want the circle on the canvas to be drawn from the top position rather than the default right.

Going clockwise (default direction arc is drawn on the canvas) from the right position, the top point is reached after three quarters, i.e. at an angle of 1.5π rad. Hence, I’ve created the variable s = 1.5 * Math.PI to later denote the starting angle for the arcs to be drawn from on the canvas.

4. Style the circle

For the drawing context object, we define the lineWidth and strokeStyle properties of the circle we are going to draw in the next step. The strokeStyle property stands for its color.

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        s = 1.5 * Math.PI,
        tc = pct = 0;

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'fuchsia';
    }
};

5. Draw the circle

We add a click event handler to the Load button [#lbtn] which triggers a setInterval timer of 60 milliseconds, that executes the function responsible for drawing the circle [updateLoader()] every 60ms till the circle is fully drawn.

The setInterval() method returns a timer id to identify its timer which is assigned to the tc variable.

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        s = 1.5 * Math.PI,
        tc = pct = 0,
        btn = document.querySelector('#lbtn');

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'fuchsia';

        btn.addEventListener('click', function() {
            tc = setInterval(updateLoader, 60);
        });
    }
};

6. Create the updateLoader() custom function

It’s time to create the custom updateLoader() function that is to be called by the setInterval() method when the button is clicked (the event is triggered). Let me show you the code first, then we can go along with the explanation.

function updateLoader() {
    ctx.clearRect(0, 0, 16, 16);
    ctx.beginPath();
    ctx.arc(8, 8, 6, s, (pct * 2 * Math.PI / 100 + s));
    ctx.stroke();

    if (pct === 100) {
        clearInterval(tc);
        return;
    }

    pct++;
}

The clearRect() method clears the rectangular area of the canvas defined by its parameters: the (x, y) coordinates of the top-left corner. The clearRect(0, 0, 16, 16) line erases everything in the 16*16 pixels canvas we have created.

The beginPath() method creates a new path for the drawing, and the stroke() method paints on that newly created path.

At the end of the updateLoader() function, the percentage count [pct] is incremented by 1, and prior to the increment we check if it equals to 100. When it’s 100 percent, the setInterval() timer (identified by the timer id, tc) is cleared with the help of the clearInterval() method.

The first three parameters of the arc() method are the (x, y) coordinates of center of the arc and its radius. The fourth and fifth parameters represent the start and end angles at which the drawing of the arc begins and ends.

We already decided the starting point of the loader circle, which is at the angle s, and it’ll be the same in all the iterations.

The end angle however will increment with the percent count, we can calculate the size of the increment in the following way. Say 1% (the value 1 out of 100) is equivalent to angle α out of 2π in a circle (2π = angle of the whole circumference), then the same can be written as the following equation:

1/100 = α/2π

On rearranging the equation:

α = 1 * 2π /100
α = 2π/100

So, 1% is equivalent to the angle 2π/100 in a circle. Thus, the end angle during each percent increment is computed by multiplying 2π/100 by the percentage value. Then the result is added to s (start angle), so the arcs are drawn from the same starting position every time. This is why we used the pct * 2 * Math.PI / 100 + s formula to calculate the end angle in the code snippet above.

7. Add the favicon

Let’s place a favicon link element into the HTML <head> section, either directly or via JavaScript.

<link rel="icon" type="image/ico" >

In the updateLoader() function, first we fetch the favicon using the querySelector() method, and assign it to the lnk variable. Then we need to export the canvas image every time an arc is drawn into an encoded image by using the toDataURL() method, and assign that data URI content as the favicon image. This creates an animated favicon which is the same as the canvas loader.

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        s = 1.5 * Math.PI,
        tc = pct = 0,
        btn = document.querySelector('#lbtn'),
        lnk = document.querySelector('link[rel="icon"]');

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'fuchsia';

        btn.addEventListener('click', function() {
            tc = setInterval(updateLoader, 60);
        });
    }
};

function updateLoader() {
    ctx.clearRect(0, 0, 16, 16);
    ctx.beginPath();
    ctx.arc(8, 8, 6, s, (pct * 2 * Math.PI / 100 + s));
    ctx.stroke();

    lnk.href= cv.toDataURL('image/png');

    if (pct === 100) {
        clearTimeout(tc);
        return;
    }

    pct++;
}

You can have a look at the full code on Github.

Bonus: Use the loader for async events

When you need to use this canvas animation in conjunction with a loading action in a web page, assign the updateLoader() function as the event handler for the progress() event of the action.

For instance, our JavaScript will change like this in AJAX:

onload = function() {
    cv = document.querySelector('#cvl'),
    ctx = cv.getContext('2d');

    if (!!ctx) {
        s = 1.5 * Math.PI,
        lnk = document.querySelector('link[rel="icon"]');

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'fuchsia';
    }

    var xhr = new XMLHttpRequest();
    xhr.addEventListener('progress', updateLoader);
    xhr.open('GET', 'https://xyz.com/abc');
    xhr.send();
};

function updateLoader(evt) {
    ctx.clearRect(0, 0, 16, 16);
    ctx.beginPath();
    ctx.arc(8, 8, 6, s, (evt.loaded*2*Math.PI/evt.total+s));
    ctx.stroke();

    lnk.href = cv.toDataURL('image/png');
}

In the arc() method, replace the percentage value [pct] with the loaded property of the event—it denotes how much of the file has been loaded, and in place of 100 use the total property of the ProgressEvent, which denotes the total amount to be loaded.

There’s no need for setInterval() in such cases, as the progress() event is automatically fired as the loading progresses.

The post How to Create an Animated Favicon Loader with JavaScript appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/animated-favicon-loader-javascript/feed/ 2 28847
10 Useful Firefox Developer Tools You Should Know https://www.hongkiat.com/blog/firefox-developers-tools/ https://www.hongkiat.com/blog/firefox-developers-tools/#comments Wed, 20 Nov 2019 13:11:33 +0000 https://www.hongkiat.com/blog/?p=25089 Firefox being "developer’s browser" has many great tools to help make our work easier. You can find more on its tool collection on the Firefox Developer Tools webpage and can also try their Developer Edition Browser which has more features and tools that are being tested. For this post, I’ve listed 10 handy tools you…

The post 10 Useful Firefox Developer Tools You Should Know appeared first on Hongkiat.

]]>
Firefox being "developer’s browser" has many great tools to help make our work easier. You can find more on its tool collection on the Firefox Developer Tools webpage and can also try their Developer Edition Browser which has more features and tools that are being tested.

For this post, I’ve listed 10 handy tools you might like from its developer tools collection. I’ve also demonstrated what these tools can do with GIFs plus how to access them for quick reference.

1. View horizontal and vertical rulers

Firefox tool - ruler

Firefox has a ruler tool that displays both horizontal and vertical rulers with pixel units on the page. The tool is useful for arranging your elements across the page.

To access rulers through the menu:

  1. Go to: ☰ > Developer > Developer Toolbar (shortcut: Shift + F2).
  2. Once the toolbar appears at the bottom of the page, type rulers.
  3. Pess Enter.

To make this appear on the developer tools window:

  1. Go to "Toolbox Options".
  2. Under the "Available Toolbox Buttons" section, check the "Toggle rulers for the page" checkbox.

2. Take screenshots using CSS selectors

Firefox tool - screenshot

Although the Firefox toolbar lets you take screenshots of the full page or visible portions, in my opinion the CSS selector method is more useful for capturing screenshots of individual elements as well as for elements that are visible on mouse-hover only (like menus).

To take screenshots through the menu:

  1. Go to ☰ > Developer > Developer Toolbar (shortcutShift + F2).
  2. Once the toolbar appears at the bottom of the page, type screenshot --selector any_unique_css_selector.
  3. Press enter.

To make this appear on the developer tools window:

  1. Click "Toolbox Options" and under "Available Toolbox Buttons" section.
  2. Check "Take a fullpage screenshot" checkbox.

3. Pick colors from web pages

Firefox tool - colorpicker

Firefox has a built-in color picker tool by the name of "Eyedropper".

To access the "Eyedropper" tool through menu go to ☰ > Developer > Eyedropper.

To make this appear on the developer tools window: click "Toolbox Options" and under "Available Toolbox Buttons" section check "Grab a color from the page" checkbox.

4. View page layout in 3D

Firefox tool - 3d view

Viewing webpages in 3D helps with layout problems. You’ll be able to see the different layered elements much more clearly in 3D view. To view the webpage in 3D, click the "3D View" tool button.

To make this appear on the developer tools window, click "Toolbox Options" and under "Available Toolbox Buttons" section check the"3D View" checkbox.

5. View browser style

Firefox tool - browser style

Browser Styles consist of two types: the default style a browser assigns for every element, and the browser-specific styles (the ones with the browser prefix). By taking a look at the browser styles you’ll be able to diagnose any override issues in your stylesheet and also come to know of any existing browser specific styles .

To access "Browser styles" through menu:

  1. Go to ☰ > Developer > Inspector.
  2. Click the "Computed" tab in the right section.
  3. Check the "Browser styles" checkbox.

You can also open the "Inspector" tab through the shortcut Ctrl +Shift + C and then accessing "Browser styles".

6. Disable JavaScript for current session

Firefox tool - disable JS

For best practice and screen reader compatibility it is always advised to code any website in such a way that its functionality is not hindered in a javascript-disabled environment. To test for such environments, you can disable the JavaScript for the session you’re working in.

To disable JavaScript for current session click "Toolbox Options" and under "Advanced settings" section check the "Disable JavaScript*" checkbox.

7. Hide CSS style from the page

Firefox tool - disable style

Just like JavaScript, due to accessibility concerns it is best to design websites in such a way that the pages should still be readable even without any styles. To see how the page looks without any style, you can disable them in the developer tools.

To remove any CSS style (inline, internal or external) applied on a webpage, just click on the eye symbol of the listed stylesheets in the "Style Editor" tab. Click it again to revert to the original view.

To access "Style Editor" through menu go to ☰ > Developer > Style Editor (shortcut: Shift + F7.

8. Preview the HTML content response to a request

Firefox tool - preview response

Firefox developer tools has an option to preview the HTML content type responses. This helps the developer to preview any 302 redirects and check whether any sensitive information has been rendered or not in the response.

To access "Preview" through menu:

  1. Go to ☰ > Developer > Network (shortcut: Ctrl +Shift + Q.
  2. Open the webpage of your choice or reload the current page, click on the desired request (with HTML response) from the list of requests.
  3. Click the "Preview" tab in the right section.

9. Preview webpage in different screen sizes

Firefox tool - responsive

To test a webpage for its responsiveness use the "Responsive Design View", which can be accessed by ☰ > Developer > Responsive Design View or with the shortcut: Ctrl +Shift + M.

To make the "Responsive Design Mode" tool button appear, click "Toolbox Options" and under the "Available Toolbox Buttons" section, check "Responsive Design Mode" checkbox.

10. Run JavaScript on pages

Firefox tool - responsive

For quick JavaScript executions on any webpage simply use the "Scratchpad" tool of Firefox. To access "Scratchpad" through the menu go to; ☰ > Developer > Scratchpad or use the keyboard shortcut Shift + F4.

To make the "Scratchpad" tool button appear on the developer tools window for quick use: click "Toolbox Options" and under the "Available Toolbox Buttons" section check the "Scratchpad" checkbox.

The post 10 Useful Firefox Developer Tools You Should Know appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/firefox-developers-tools/feed/ 5 25089
Advanced Checkbox Styling with CSS Grid https://www.hongkiat.com/blog/advanced-checkbox-styling/ https://www.hongkiat.com/blog/advanced-checkbox-styling/#respond Tue, 22 Oct 2019 13:43:06 +0000 https://www.hongkiat.com/blog/?p=38877 The CSS Grid Layout Module can not only solve a mammoth of a layout problem but also some good old mulish issues we’ve been dealing with for a long time, such as styling a checkbox label. While there’s a relatively straightforward method to style the label when it appears after the checkbox, it’s not that…

The post Advanced Checkbox Styling with CSS Grid appeared first on Hongkiat.

]]>
The CSS Grid Layout Module can not only solve a mammoth of a layout problem but also some good old mulish issues we’ve been dealing with for a long time, such as styling a checkbox label.

While there’s a relatively straightforward method to style the label when it appears after the checkbox, it’s not that easy when the label appears before it.

Checkbox styling without CSS Grid

Styling a label after a checkbox is something us developers have been doing ever since we read about it somewhere. This technique is one of the prime and old examples of the powerful dynamics that CSS can possess.

Here’s the code you already might be familiar with, that styles a label after a checked checkbox:

<input type="checkbox">
<label>label for the checkbox</label>
input:checked + label {
  /* style me */
}

A styled label after a checkbox might look like this (however, you can use other style rules as well):

Styling label without the CSS Grid

The above CSS code uses the adjacent sibling combinator marked by the + key. When a checkbox is in the :checked state, an element after it (usually a label) can be styled using this method.

Such a simple and effective technique! What could possibly go wrong with it? Nothing—until you want to display the label before the checkbox.

The adjacent sibling combinator selects the next element; this means the label has to come after the checkbox in the HTML source code.

So, to make a label appear before the belonging checkbox on the screen, we can’t just move it before the checkbox in the source code, as a previous sibling selector doesn’t exist in CSS.

Which leaves only one option: repositioning the checkbox and the label using transform or position or margin or another CSS property with some kind of telekinetic power, so that the label appears to the left of the checkbox on the screen.

Problems with the traditional method

There’s nothing majorly wrong with the aforementioned technique but it can be inefficient in certain cases. I mean cases in which the rearranged positions of the checkbox and the label don’t work anymore.

Think responsive, for instance. You might have to resize or reposition the checkbox according to the device it’s displayed on. When that happens, you will need to reposition the label as well, as there’ll be no automatic realignment done to the label in response to the repositioning/resizing of the checkbox.

We can eliminate this disadvantage if we could just provide some solid layout for the checkbox and the label, instead of roughly positioning them on the page.

But, almost all layout systems, such as tables or columns, require you to add the label before the checkbox in the source code to make it appear the same way on screen. That’s something we don’t want to do because the next element selector on the label will stop working.

CSS Grid, on the other hand, is a layout system that is not dependent on the placement/order of elements in the source code.

The reordering capabilities of grid layout intentionally affect only the visual rendering, leaving speech order and navigation based on the source order. This allows authors to manipulate the visual presentation while leaving the source order intact… – CSS Grid Layout Module Level 1, W3C

Thus, CSS grid is an ideal solution to style the label that appears before the checkbox.

Checkbox styling with CSS Grid

Let’s start with the HTML code. The order of the checkbox and label will remain the same as before. We just add both of them to a grid.

<div id="cbgrid">
  <input type="checkbox">
  <label>label for the checkbox</label>
</div>

The accompanying CSS is as follows:

#cbgrid {
  display: grid;
  grid-template-areas: "left right";
  width: 150px;
}
input[type=checkbox] {
  grid-area: right;
}
label {
  grid-area: left;
}

I’ll not go in depth on how the CSS grid works, as I already wrote a detailed article on the subject, that you can read here. Some basics, however: the display: grid property turns an element into a grid container, grid-area identifies the grid area an element belongs to, and grid-template-areas forms a grid layout, comprised of different grid areas.

In the above code, there are two grid areas: "left" and "right". They make up two columns of a grid row. The checkbox belongs to the "right" area and the label to the "left". Here’s how they look on screen:

Styling label with the CSS Grid

Since we didn’t change the relative placement of the checkbox and the label in the source code, we can still use the adjacent sibling combinator:

input:checked + label {
  /* style me */
}

Note that a grid item is always blockified; it appears with a surrounding box known as the grid-level box. If you don’t want that, for instance for a label, put a wrapper on that item (wrap it in another element) and turn that wrapper into the grid area.

That’s it, folks. CSS grid hopefully helps you nail down the layouts of those cheeky checkboxes.

The post Advanced Checkbox Styling with CSS Grid appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/advanced-checkbox-styling/feed/ 0 38877
How to Display Text on Image With CSS3 mix-blend-mode https://www.hongkiat.com/blog/css3-mix-blend-mode/ https://www.hongkiat.com/blog/css3-mix-blend-mode/#comments Mon, 14 Oct 2019 13:17:42 +0000 https://www.hongkiat.com/blog/?p=28201 Image backgrounds look great behind large display texts. However, its CSS implementation is not that straightforward. We can use the background-clip: text; property, however it’s still an experimental feature without sufficient browser support. The CSS alternative to show an image background behind a text is using the mix-blend-mode property. Blend modes for HTML elements are…

The post How to Display Text on Image With CSS3 mix-blend-mode appeared first on Hongkiat.

]]>
Image backgrounds look great behind large display texts. However, its CSS implementation is not that straightforward. We can use the background-clip: text; property, however it’s still an experimental feature without sufficient browser support.

The CSS alternative to show an image background behind a text is using the mix-blend-mode property. Blend modes for HTML elements are fairly supported across all modern desktop and mobile browsers with the exception of a few, such as Internet Explorer.

In this post, we’re going to see how mix-blend-mode (two of its modes specifically) works, and how you can use it to display a text with image background in two use cases:

  1. when the background image can be seen through the text
  2. when the background image runs around the text

See some examples in the demo below (images are from unsplash.com).

The mix-blend-mode CSS property defines how the content and the backdrop of an HTML element should blend together colorwise.

Have a look at the list of blending modes, out of which we’ll use multiply and screen in this post.

First, let’s look into how these two specific blend modes work.

How multiply & screen blend modes work

Blending modes technically are functions that calculate a final color value using the color components of an element and its backdrop.

The multiply blend mode

In the multiply blend mode, the individual colors of the elements and their backdrops are multiplied, and the resulting color is applied to the final blended version.

The multiply blend mode is calculated according to the following formula:

B(Cb, Cs) = Cb × Cs

where: Cb – Color component of the backdrop Cs – Color component of the source element B – Blending function

When Cb and Cs are multiplied, the resulting color is a blend of these two color components, and is as dark as the darkest of the two colors.

To create our text image background, we need to focus on the case when Cs (the color component of the source element) is either black or white.

If Cs is black its value is 0, the output color will also be black, because Cb × 0 = 0. So, when the element is colored black, it doesn’t matter what color the backdrop is, all we can see after blending is black.

If Cs is white its value is 1, the output color is whatever Cb is, becauseCb × 1 = Cb. So in this case we see the backdrop directly as it is.

The screen blend mode

The screen blend mode works similarly to the multiply blend mode, but with the opposite result. So, a black foreground shows the backdrop as it is, and a white foreground shows white with whatever backdrop.

Let’s quickly see its formula:

B(Cb, Cs) = Cb + Cs - (Cb × Cs)

When Cs is black (0), the backdrop color will be shown after the blending, as:

Cb + 0 - (Cb × 0) = Cb + 0 - 0 = Cb

When Cs is white (1) the result will be white with any backdrop, as:

Cb + 1 -(Cb × 1) = Cb + 1 - Cb = 1

1. Image shown through text

To display text showing through its background image, we use the screen blend mode with black text and white surrounding space.

<div class="backdrop">
 <p class="text">Water</p>
</div>
.backdrop {
 width: 600px; height: 210px;
 background-image: url(someimage.jpg);
 background-size: 100%;
 margin: auto;
}
.text {
 color: black;
 background-color: white;
 mix-blend-mode: screen;
 width: 100%;
 height: 100%;
 font-size: 160pt;
 font-weight: bolder;
 text-align: center;
 line-height: 210px;
 margin: 0;
}

Currently our text looks like below, in the next step we’ll add custom color to the background.

Image Shown Through Text without Color
Adding color

As you might’ve guessed by now, using blend modes leave us only two color choices for the area that surrounds the text — black or white. However with white, it’s possible to add some color to it using an overlay, if the overlay color matches nicely with the image used.

To add color to the surrounding area, add a <div> to the HTML for an overlay, and give it a background color with high transparency. Also use the mix-blend-mode: multiply property for the overlay, as it helps the background color of the overlay to blend a bit better with the image appearing inside text.

<div class="backdrop">
 <p class="text">Water</p>
 <div class="overlay"></div>
</div>
.overlay {
 background-color: rgba(0,255,255,.1);
 mix-blend-mode: multiply;
 width: 100%;
 height: 100%;
 position: absolute;
 top: 0;
}

With this technique, we could color the surrounding area around the text with the image background:

Image Shown Through Text with Blue Background

Note that the technique works well only with subtle transparent colors. If you use a fully opaque color, or a color that doesn’t match with the image, the image appearing inside the text will have a very visible tint of the color used, so unless it’s a look that you’re going for, avoid opaque colors.

2. Text surrounded by image background

Even though a normal text placement over an image background requires the same technique, I’m going to show you an example of how the above demo looks like when the effect is reversed, i.e. when the text color is white and the background is black.

.text {
 color: white;
 background-color: black;
 mix-blend-mode: screen;
 width: 100%;
 height: 100%;
 font-size: 160pt;
 font-weight: bolder;
 text-align: center;
 line-height: 210px;
 margin: 0;
}

You can use the same overlay in order to add some color to the text, unless you want to keep it white.

.overlay {
 background-color: rgba(0,255,255,.1);
 mix-blend-mode: multiply;
 width: 100%;
 height: 100%;
 position: absolute;
 top: 0;
}

And below you can see how the reverse case looks like:

Text Surrounded By Image

Note that in Internet Explorer, or any other browser that doesn’t support the mix-blend-mode property, the image background won’t appear, and the text will remain black (or white).

The post How to Display Text on Image With CSS3 mix-blend-mode appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/css3-mix-blend-mode/feed/ 3 28201