Javascript

GitBook docs section concerning Javascript context.

Scroll Display Function

Scroll Display Function: blocks only appear when you scroll to their position.

var vid = document.getElementById("video-corporate");
function isScrolledIntoView(element) {
    var elementTop = element.getBoundingCLientRect().top;
    var elementBottom = element.getBoundingClientRect().bottom;
    return (elementTop + 300) >= 0 && (elementBottom - 300) <= window.innerHeight;
}
windows.addEventListener("scroll", function() {
    if (isScrolledIntoView(vid)) {
        vid.play();
    }
    else {
        vid.pause();
    }
});

Add CSS Class

Add CSS class with javascript.

A more efficient method is to put those styles into a class, and then add that class onclick, like this:

Array to Table

Generate tabble from javascript array.

Vanilla Javascript Solution

jQuery Solution

Ready vs Load

document.ready

document.ready will execute right after the HTML document is loded properly, and the DOM is ready.

window.load

window.load will wait for the page to be fully loaded, this includes inner iframes, images, etc.

User-Agent Localization

An IP address lookup is a way to get the location of websiate visitors. We usually use public IP lookup services/APIs for this solution. Some of this are paid services and some are free. Examples include IP Geolocation API, IPinfo and GEOIP DB. They provide the data in various formats as well, such as JSON, XML and CSV. We'll be using IP Geolocation API for this example.

Web Component

Web Components are a set of features that provide a standard component model for the Web[1] allowing for encapsulation and interoperability of individual HTML elements.

Create a custom element

We begin to create the basic structure of our component by creating a rating.js file and inserting the following javascript code inside:

This code allows us to lay the foundation in the creation of what is called a custom element, that is a custom HTML element. A fundamental requirement for the name to be assigned to a custom element to be valid is that it contains a hyphen inside it, as in our example. The following is a list of expected reactions for a component:

  • contructor(): While this is not a real custom element reaction, it is important to understand that its code is executed when an instance of the component is created; at this stage it is possible to make state initializations or event handler assignments; however, it is not possible to refer to the DOM

  • connectedCallback(): This method is invoked whenever an instance of the component is inserted into the DOM; setup operations such as changing the DOM can be performed at this stage

  • disconnectedCallback(): The method is invoked when the component is removed from the DOM

  • attributeChangedCallback(): It is executed when an attribute associated with the component is modified; only observed attributes generate the invocation of this method

  • adoptedCallback(): This method is invoked when the element is adopted from another document via the document.adoptNode() method

Once the component is defined, we can use it in an HTML page as shown by the following example:

In the body of the page we used our component as a normal HTML element. We point out that it is not possible to use the notation for empty elements for custom elements.

Adding Markup and CSS

Once we have introduced the basic principles on which the definition of a custom element rests, we begin to build the structure of our component by defining its markup and CSS. We structure our component in such a way as to expose properties that can be manipulated from the outside, through standard getter and setter of javascript class, as shown below:

With these changes, the initialization code of our component, will have the expected effect, that is, it will make sure that a total of six stars are displayed, two of which are internally colored:

Or:

Manage events

To make our component really useful, let's try to add a little interactivity. We will ensure that the user can express his rating by clicking on one of the stars displayed. To achieve this, simply change the createStar() function and createStarList() function code as shown below:

Loader AJAX Call

Display Loading Image or loader when AJAX call is in Progress.

Syntax

This executes when AJAX request is finished whether it successfully callback or not.

Example

Image Comparison Slider

Move the slider to compare images.

HTML

CSS

Javascript

Adding Print Button to HTML

Adding a Print Button

You can easily add a print button to your web page by adding the following code to your HTML document where you want the button to appear:

The button will be labeled as Print this page when it appears on the web page. You can customize this text to whatever you like by changing the text between the quotation marks following:

in the code above.

It's even easier to add a simple print link to your web page. Just insert the following code into your HTML document where you want the link to appear:

You can customize the link text by changing "print" to whatever you choose.

Making Specific Sections Printable

You can set up the ability for users to print specific parts of your web page using a print button or link. You can do this by adding a print.ess file to your site, calling it in the head of your HTML document and then defining those sections you want to make easily printable by defining a class.

First, add the following code to the head section of your HTML document:

Next, create a file named print css. In this file, add the following code:

This code defines all elements in the body as hidden when being printed unless the element has the "print" class assigned to it.

Now, all you need to do is to assign the "print" class to the elements of your web page that you want to be printable.

Anything else on the page that is not assigned to this class will not print.

Enter Key Pressed for Custom Event in HTML formats

The code snippet listens for the Enter key press within the HTML element with the ID form-id. When the Enter key is pressed, it displays an alert message and prevents the form from being submitted. This is often used to handle user input in a specific way or to trigger custom actions when the user presses Enter within a form field.

Useful Javascript Console Commands

1. console.log()

The first and most common command is the console.log() command. It takes in a message and prints out the result to the console. It can also print JavaScript objects, arrays - all data types in JavaScript. Additionally, it takes care of formatting the output of the result to make it easier to trace.

console-log

2. console.error()

The console.log() command is used by developers for most of the things they do - including logging errors to the console. But do you know there is a special console command for that ? It is the console.error() command. It is very similar to the console.log() command except it wraps what you log in a red error box.

console-error

3. console.info()

This console command is especial useful to output information to the console. Rather than using console.log(), you will use console.info() to make the information stand out from other console commands.

console-info

4. console.table()

When dealing with arrays, you usually like to represent it in an easy to understand structure. The console.table() commands handles that for you.

console-table

5. console.assert()

This console command writes an error message to the console if an evaluates condition is false.

console-assert

6. console.clear()

This command clears the console for you.

7. & 8. console.group() and console.groupEnd()

These two console commands are useful to group stuff together in the console.

The console.group() is used to start a group. The group will continue until it encounters a console.groupEnd(). console-group

9. console.warn()

Logging warnings in the console should be easy! Thats why the console.warn() command exists.

console-warn

10. & 11. console.time() and console.timeEnd()

There will be times when you will ned to measrue the time taken for an operation to complete. For this situations, you can make use of teh console.time() and console.timeEnd() functions. You use the console.time() to start a timer and console.timeEnd() to stop the timer.

console-time

Last updated