Skip to main content

Vanilla script

This function gets the cookie specified:-

function gcook(cookieName) {
        /**
         * This variable holds the array of available cookies
         */
        var cookies = document.cookie.split(";");
        cookieName += "=";
        for (var i = 0; i < cookies.length; i++) {
            var c = cookies[i].trim();
            if (c.indexOf(cookieName) == 0) {
                /**
                 * This statement retrieves the value of the specified cookie
                 */
                return c.substring(cookieName.length, c.length);
            }
        }
        return null;
    }




This function sets a cookie with specified name, value and for certain time:-

    function scook(cookie) {
        var exdate = new Date();
        /**
         * This statement sets the date when the cookie will be removed from the client machine
         */
        exdate.setDate(exdate.getDate() + cookie.time);
        var c_value = cookie.value + (cookie.time == null ? "" : ";expires=" + exdate.toUTCString());
        document.cookie = cookie.name + "=" + c_value;
    }





This function scrolls the document to the top within specified time in ms:-

    function scrollToTop(duration) {
        /**
         * This variable holds the scrolling steps which will be scrolled upto each the the specified duration is reached and the whole page is scrolled to the top within the specified duration
         */
        var scroll = -window.scrollY / ((duration / 15));
        var tID = setInterval(function () {
            if (window.scrollY > 0) {
                window.scrollBy(0, scroll);
            } else {
                /**
                 * This statement stops the further code repetition as the page is being successfully scrolled to the very top
                 */
                clearInterval(tID);
            }
        }, 15);
    }
 
Here is a method using AJAX for form submission in javascript:-
 
var ajax={}, message={
    "output": null, 
    "error": null,
    "state": null,
    "loaded": 0,
    "total": 0
};
ajax.defaultSettings={
    method: "GET",
    url: "",
    data: [],
    async: true,
    percentageID: "percentage",
    contentType: "application/x-www-form-urlencoded",
    onprogress: function(message){
        return false;
    },
    onsuccess: function(message){
        return false;
    },
    onerror: function(message){
        return false;
    }
}
function AJAX(settings){
    var info="";
    if(settings.method==null){
        settings.method=ajax.defaultSettings.method;
    }
    settings.method=settings.method.toUpperCase();
    if(settings.method!=="GET" && settings.method!=="POST"){
        throw "Please specify a valid method for ajax request";
    }
    if(settings.url==null){
        throw "Please specify the URL to which the request has to be sent";
    }
    if(settings.data==null){
        throw "Please specify the data you want to send";
    }
    if(settings.percentageID==null){
        settings.percentageID=ajax.defaultSettings.percentageID;
    } else{
        ajax.defaultSettings.percentageID=settings.percentageID;
    }
    if(settings.async==null){
        settings.async=ajax.defaultSettings.async;
    }
    if(settings.contentType==null){
        settings.contentType=ajax.defaultSettings.contentType;
    }
    var data, elems;
    elems=Object.keys(settings.data).length
    for(data in settings.data){
        info+=data+"="+encodeURIComponent(settings.data[data]);
        if(elems>1)
            info+="&";
        elems--;
    }
    var handler;
    if(window.XMLHttpRequest){
        handler=new XMLHttpRequest();
    } else{
        handler=new ActiveXObject("Microsoft.XMLHTTP");
    }
    message.state=handler.readyState;
    handler.addEventListener("progress", updateProgress, false);
    if(settings.async==true){
        handler.onreadystatechange=function(){
            if(handler.readyState==4 && handler.status==200){
                message.output=handler.responseText;
                message.error=null;
                message.state=4;
                handler.onsuccess=settings.onsuccess(message);
            } else if(handler.readyState==4 && handler.status==404){
                message.output=null;
                message.error="Page Not Found";
                message.state=4;
                handler.onerror=settings.onerror(message);
            }
        }
    }
    if(settings.method==="GET"){
        handler.open("GET", settings.url+"?"+info, settings.async);
        handler.send();
    } else{
        handler.open("POST", settings.url, settings.async);
        handler.setRequestHeader("Content-type", settings.contentType);
        handler.setRequestHeader("Content-length", info.length);
        handler.setRequestHeader("Connection", "Close")
        handler.send(info);
    }
}
function updateProgress(event){
    message.loaded=event.loaded;
    message.total=event.total;
    settings.onprogress(message);
}
 
Here is how you can use your custom query selector in javascript:-
window.$=function(selector){
            return document.querySelector(selector);
        }

Comments

Popular posts from this blog

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Java Program to calculate the Strike Rate of a Cricket Batsman

import java.io.*; import java.util.*; public class StrikeRate{     Scanner scan=new Scanner(System.in);     int ballsFaced, runs;     double strikeRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Faced: ");             ballsFaced=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0); ...

WP similar or related posts widget without using any plugin

Hi guys, Recently I was working on some WP website and my client told me that he required a widget for displaying related/similar posts on the single post page. But as his website was already using many plugins, even for some pretty small tasks like this one, I decided not to use another WP plugin (plugins are not good for your WP websites, we will discuss about that on some other post.) I am not explaining the code as it is pretty simple if you are familiar with WP classes. But please let me know if you have any questions related to the PHP code posted below in the comments section or even much better, on Gist. You can add the following code directly in your child theme's functions.php file or you can create a separate file and include this at the bottom of functions.php file. <?php class similar_posts_widget extends WP_Widget {     function __construct()     {         parent::__construct('similar_posts_...