JAVASCRIPT Docs

Last updated: Jan 20th, 2022

Download

Welcome to the mine useful documentation for daily work on web developer and computer programming. Thanks to PrettyDocs for theme template layout; download it at the page linked in the button below.

Download PrettyDocs

PrismJS

PrismJS is used as the syntax highlighter here. You can build your own version via their website should you need to.

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.


$('#image').click(function() {
    $('#text').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});
                                    

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


$('#image').click(function() {
    $('#text').addClass('myClass');
});
                                    

Array to Table

Generate tabble from javascript array.

Javascript Solution

var rows = [{
    name: 'Jhon',
    age: 20,
    email: 'jhon@gmail.com'
}, {
    name: 'Jack',
    age: 50,
    email: 'jack@gmail.com'
}, {
    name: 'Jim',
    age: 35,
    email: 'jim@gmail.com'
}];

var html = '<tr border="1|1">';
for (let i = 0; i < rows.length; i++) {
    html += '<tr>';
    html += '<td>' + rows[i].name + '</td>';
    html += '<td>' + rows[i].age + '</td>';
    html += '<td>' + rows[i].email + '</td>';
    html += '</tr>';
}
html += '</table>';
document.getElementById('box').innerHTML = html;
                                    
jQuery Solution

var rows = [{
    name: 'Jhon',
    age: 20,
    email: 'jhon@gmail.com'
}, {
    name: 'Jack',
    age: 50,
    email: 'jack@gmail.com'
}, {
    name: 'Jim',
    age: 35,
    email: 'jim@gmail.com'
}];

$(document).ready(function() {
    var html = '<tr border="1|1">';
    for (let i = 0; i < rows.length; i++) {
        html += '<tr>';
        html += '<td>' + rows[i].name + '</td>';
        html += '<td>' + rows[i].age + '</td>';
        html += '<td>' + rows[i].email + '</td>';
        html += '</tr>';
    }
    html += '</table>';
    $('box').html(html);
});
                                    

Ready vs Load

document.ready

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


$(document).ready(function() {
    // executes when HTML-Document is loaded and DOM is ready
    alert("(document).ready was called - document is ready!");
});
                                    
window.load

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


$(window).load(function() {
    // executes when complete page is fully loaded, including all frames, objects and images
    alert("(window).load was called - window is loaded!");
});
                                    

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.


function ipLookUp() {
    $.ajax('http://ip-api.com/json')
    .then(
        function success(response) {
            console.log("User\'s Location Data is ", response);
            console.log("User\'s  Country", response.country);
        },
        function fail(data, status) {
            console.log("Request failed. Return status of ", status);
        }
    );
}

ipLookUp();
                                    

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:


class MyRating extends HTMLElement {
    constructor() {
        super();
    }
    connectedCallback() {
        this.innerText = "Here I am!";
    }
}
customElements.define("my-rating", MyRating);
                                    

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:


<!DOCTYPE html>
<html>
    <head>
        <script src="rating.js"></script>
    </head>
    <body>
        <my-rating></my-rating>
    </body>
</html>
                                    

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:


const styleRules = `
.rating {
    color: orange;
}`;

class MyRating extends HTMLElement {
    constructor() {
        super();
        this._maxValue = 5;
        this._value = 0;
        this.attachShadow({mode: "open"});
    }

    connectedCallback() {
        this.createComponent()
    }

    get maxValue() {
        return this._maxValue;
    }
    set maxValue(val) {
        this._maxValue = val;
        this.setAttribute("max-value", val);
    }

    get value() {
        return this._value;
    }
    set value(val) {
        this._value = val;
        this.setAttribute("value", val);
    }

    static get observedAttributes() {
        return ["max-value", "value"];
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue !== newValue) {
            switch (name) {
                case "max-value":
                    this._maxValue = newValue;
                    break;
                case "value":
                    this._value = newValue;
                    break;
            }
            this.replaceStarList();
        }
    }

    replaceStarList() {
        let starNode = this.shadowRoot.children[1];
        if (starNode) {
            let starList = this.createStarList();
            starNode.remove();
            this.shadowRoot.appendChild(starList);
        }
    }

    createComponent() {
        let style = document.createElement("style");
        style.appendChild(document.createTextNode(styleRules));
        this.shadowRoot.appendChild(style);
        let starList = this.createStarList();
        this.appendChild(starList);
    }

    createStarList() {
        let div = document.createElement("div");
        let star;
        for (let i = 1; i <= this.maxValue; i++) {
            if (i <= this.value) {
                star = this.createStar("&#x2605;"); 
                div.appendChild(span);
            }
            else {
                star = this.createStar("&#x2606;");
            }
            div.appendChild(star);
        }
        return div;
    }

    createStar(starCode) {
        let span = document.createElement("span");
        span.setAttribute("class", "rating");
        span.innerHTML = starCode;
        return span;
    }
}

customElements.define("my-rating", MyRating);
                                    

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:


<html>
    <head>
        ...
        <script>
                        window.onload = function() {
                            let myRatingComponent = document.getElementById("myRatingComponent");
                            myRatingComponent.maxValue = 6;
                            myRatingComponent.value = 2;
                        }
                </script>
    </head>
    <body>
        ...
    </body>
</html>
                                    

Or:


<my-rating id="myRatingComponent" max-value="6" value="2"></my-rating>
                                    
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:


createStar(starCode, index) {
    let span = document.createElement("span"); 
    span.setAttribute("class", "rating"); 
    span.addEventListener("click", () => {
        this.setAttribute("value", index);
    });
    span.innerHTML = starCode;
    return span;
}
                                    

createStarList() {
    let div = document.createElement("div");
    let star;
    for (let i = 1; i <= this.maxValue; i++) {
        if (i <= this.value) {
            star = this.createStar("&#x2605;", i); 
            div.appendChild(span);
        } else {
            star = this.createStar("&#x2606;", i);
        }
        div.appendChild(star);
    }
    return div;
}
                                    

Loader AJAX Call

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

Syntax

$.ajax({
    ...
    beforeSend: function(){
        /* Statement */
    }
    ...
});
complete
                                    

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

Example

<script type='text/javascript'>
$(document).ready(function(){
    
    $("#but_search").click(function(){
        var search = $('#search').val();

        $.ajax({
            url: 'fetch_deta.php',
            type: 'post',
            data: {search:search},
            beforeSend: function(){
                /* Show image container */
                $("#loader").show();
            },
            success: function(response){
                $('.response').empty();
                $('.response').append(response);
            },
            complete:function(data){
                /* Hide image container */
                $("#loader").hide();
            }
        });
    });
});
</script>

<input type='text' id='search'>
<input type='button' id='but_search' value='Search'><br/>

<!-- Image loader -->
<div id='loader' style='display: none;'>
    <img src='reload.gif' width='32px' height='32px'>
</div>
<!-- Image loader -->

<div class='response'></div>
                                    

Image Comparison Slider

Move the slider to compare images.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Compare Two Images</h1>

        <p>Click and slide the blue slider to compare two images:</p>

        <div class="img-comp-container">
            <div class="img-comp-img">
                <img src="img_snow.jpg" width="300" height="200">
            </div>
            <div class="img-comp-img img-comp-overlay">
                <img src="img_forest.jpg" width="300" height="200">
            </div>
        </div>

        <script>
                        /* Execute a function that will execute an image compare function for each element with the img-comp-overlay class: */
                        initComparisons();
                </script>

    </body>
</html>
                                    
CSS

* {
    box-sizing: border-box;
}

.img-comp-container {
    position: relative;
    height: 200px; /* should be the same height as the images */
}

.img-comp-img {
    position: absolute;
    width: auto;
    height: auto;
    overflow: hidden;
}

.img-comp-img img {
    display: block;
    vertical-align: middle;
}

.img-comp-slider {
    position: absolute;
    z-index: 9;
    cursor: ew-resize;
    /* set the appearance of the slider: */
    width: 40px;
    height: 40px;
    background-color: #2196F3;
    opacity: 0.7;
    border-radius: 50%;
}
                                    
Javascript

function initComparisons() {
    var x, i;
    /* find all elements with an "overlay" class: */
    x = document.getElementsByClassName("img-comp-overlay");
    for (i = 0; i < x.length; i++) {
        /* once for each "overlay" element: pass the "overlay" element as a parameter when executing the compareImages function: */
        compareImages(x[i]);
    }
    function compareImages(img) {
        var slider, img, clicked = 0, w, h;
        
        /* get the width and height of the img element */
        w = img.offsetWidth;
        h = img.offsetHeight;
        
        /* set the width of the img element to 50%: */
        img.style.width = (w / 2) + "px";
        
        /* create slider: */
        slider = document.createElement("DIV");
        slider.setAttribute("class", "img-comp-slider");
        
        /* insert slider */
        img.parentElement.insertBefore(slider, img);
        
        /* position the slider in the middle: */
        slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
        slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
        
        /* execute a function when the mouse button is pressed: */
        slider.addEventListener("mousedown", slideReady);
        
        /* and another function when the mouse button is released: */
        window.addEventListener("mouseup", slideFinish);
        
        /* or touched (for touch screens: */
        slider.addEventListener("touchstart", slideReady);
        
        /* and released (for touch screens: */
        window.addEventListener("touchend", slideFinish);
        function slideReady(e) {
            /* prevent any other actions that may occur when moving over the image: */
            e.preventDefault();
            
            /* the slider is now clicked and ready to move: */
            clicked = 1;
            
            /* execute a function when the slider is moved: */
            window.addEventListener("mousemove", slideMove);
            window.addEventListener("touchmove", slideMove);
        }
        function slideFinish() {
            /* the slider is no longer clicked: */
            clicked = 0;
        }
        function slideMove(e) {
            var pos;
            
            /* if the slider is no longer clicked, exit this function: */
            if (clicked == 0) return false;
            
            /* get the cursor's x position: */
            pos = getCursorPos(e)
            
            /* prevent the slider from being positioned outside the image: */
            if (pos < 0) pos = 0;
            if (pos > w) pos = w;
            
            /* execute a function that will resize the overlay image according to the cursor: */
            slide(pos);
        }
        function getCursorPos(e) {
            var a, x = 0;
            e = (e.changedTouches) ? e.changedTouches[0] : e;
            
            /* get the x positions of the image: */
            a = img.getBoundingClientRect();
            
            /* calculate the cursor's x coordinate, relative to the image: */
            x = e.pageX - a.left;
            
            /* consider any page scrolling: */
            x = x - window.pageXOffset;
            return x;
        }
        function slide(x) {
            /* resize the image: */
            img.style.width = x + "px";
            
            /* position the slider: */
            slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
        }
    }
}