Tag: Javascript

  • Restrict number of selected checkboxes in html

    This code will restrict html multi select input to given number.

    document.addEventListener( "click", function( event ) {
        if ( event.target.matches( '.input-checkbox' ) ) {
            var inputCheckboxes = document.querySelectorAll( '.input-checkbox[type="checkbox"]:checked' );
            if( inputCheckboxes.length > 3 ) {
                event.preventDefault();
                alert( 'You cannot select more than 3 categories for a post.' );
            }
        }
    } );
  • Why click event not working on SVG

    I created a simple menu with SVG icons and to my surprise, clicking on the icon was not taking me to the linked url.

    It turned out that as SVGs are independent HTML objects, the target element is actually nested path. So, it does not match with the clicked element and thus click event listeners does not work on it.

    Similarly, if you add others event listeners to the parent element of the SVG’s, it does not work.

    There are multiple ways to fix this-

    1. Disable click on SVG elements by adding the CSS- pointer-events: none;

    2. Add event listener to the path element of SVG.

    Problem solved.

    References:

    1. https://gomakethings.com/detecting-click-events-on-svgs-with-vanilla-js-event-delegation/
  • Add event listener on SVG element

    I was facing problem while adding event listener to an svg element.

    Then I added event listeners to both svg and path tags, and it worked.

  • Decode a PHP encoded string url in Javascript

    Sometimes you may face a problem when you have to decode a string with Javascript which was originally url encoded with PHP. This can be an API response or cookie set by PHP setcookie function.

    A simple way to do this is through decodeURIComponent function in Javascript. But it leaves the "+" signs in the string. For that we can use replace function to replace all the "+" signs with space. Remember, simply using replace function sign will only replace the first occurrence in the string. To replace all the occurrences, use the regex version with g flag.

    Here is the code for your reference-

    var decodedString = decodeURIComponent( encodedString ).replace( /+/g, ' ' );

    Here encodedString is the url encoded string received from PHP.

    Its that simple!

    If you have any other method, do share in comments.

    Happy coding!

  • Make Javascript sequential with “async” and “await”

    Most of the older programming languages are sequential in nature. That means, when the code runs, it is executed line by line. If there is a function call, the next line is executed only when the function has been executed and returned control. This is blocking in nature and helps programmers easily predict the output of their code.

    But when we move to async languages like Javascript, code is non-blocking in nature. That means, execution does not wait for any function to return response. This is good for performance, but creates a problem when the next line of code requires output from the function call made in previous line.

    To solve this problem, Javascript provides Promises. Promises allow us to write a callback function to process the response of the called function. But their syntax requires to write another function to handle the response. Also, if there are multiple functions, it may lead to callback hell.

    The syntax of a function returning a promise is:

    function add(a, b) {
        return new Promise(function(resolve, reject) {
            resolve(a+b);
        });
    }

    And this is how we handle the returned Promise:

    add(2,3).then(function(response) {
        console.log(response);
    }

    This becomes cumbersome if there are a lot of function calls nested inside one another. To simplify this code, there are two keywords in Javascript to write promises in a very simple way- async and await.

    async

    async can be placed before a function definition. It means that the function will always return a promise. If the returned value is not a promise, it will wrap it in a promise and return.

    async function demoFunction() {
        return 1;
    }

    await

    await can be placed before any line of code to ensure that Javascript hold the execution till that line is executed. If there is a function call in that line, Javascript is wait till the function returns a response.

    async function demoFunction() {
        let sum = await add(a, b);
        console.log(sum);
    }

    In the above example, we are calling a function called add and saving its value in a variable called sum. The await ensures that the next line is executed only after we get the value returned from the function add. If we remove the await keyword from this, console.log may print an empty variable.

    So, even if the called function is returning a promise, there is no need of defining any callback function. Just simply store its return value in a variable and process it in the next line of code. This is pretty much like we do stuff in C or PHP.

    Note: await can only be used inside an async function.

    This is such a simple syntax that can easily make Javascript code sequential whenever needed.

    To read the detailed description of these keywords, you can refer to the following articles: