DEV Community

Cover image for Java Script Library CompactDOM
Vladimir Kheifets
Vladimir Kheifets

Posted on

Java Script Library CompactDOM

CompactDOM is a Java Script library (CompactDOM object), the functions (methods) of which, simplify manipulating DOM elements. One character _ is alias name CompactDOM object.

The current version of CompactDOM can be downloaded from GitHub

Browser support: Chrome 4.0, Internet Explorer 10.0, Edge,Firefox 3.5, Safari 3.2, Opera 10.0

Size of the current version (file CompactDOM.min.js) 14Kb
You can find tutorial of the Java Script Library CompactDOM on the website:

https://www.alto-booking.com/developer/CompactDOM/
The open source code of the site is implemented with CompactDOM and demonstrates the use of this library.
index.html

<html>
<meta charset=utf-8>
<title>CompactDOM manual</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1, user-scalable=no, user-scalable=0" >
<meta name="description" content="CompactDOM js library online-tutorial">
<meta name="keywords" content="CompactDOM,javascript,library">
<meta name="author" content="Vladimir Kheifets">
<meta name="robots" content="index,follow" />
<script type="text/javascript" src="sections/CompactDOM.min.js"></script>
<script>
_("head").script("index.js");
</script>
</head>
<body>
<div id="block-setting">
<i id="setting" class="fas fa-cog"></i>
    <div>
    Code highlighting:<br>
    <i id="adj" class="fas fa-adjust"></i> <span id="dark-light" ></span>
    <br>Themes:<br>
    <select id="thema" ></select>
    </div>
</div>
<div class="CLB">
    <div id="Sections"></div>
    <div id="SectionsContent"></div>
</div>
<div class="footer"></div>
</div>
<script src="dist/rainbow.js"></script>
<script src="src/language/generic.js"></script>
<script src="src/language/html.js"></script>
<script src="src/language/css.js"></script>
<script src="src/language/php.js"></script>
<script src="src/language/javascript.js"></script>
<script src="src/language/json.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CompactDOM code index.js

_("head").script("themes/themes.js");
start=function()
{
    SectionsСontent = _("#SectionsСontent");
    href = themeHref(false);
    __.link({id:"color-shema",href:href, media:"screen"});
    __.link("css/index.css,css/all.css,css/modal.css,css/button_to_up.css");
    _("#modal1").modal();
    __.scroll();
    adj=_("#adj");
    dl =_("#dark-light");
    adj.click(function(){
        if(__.ins("light",dl.content()))
        {
            adj.css("transform: rotate(360deg)")
            dl.content("dark code");
            light_theme = false;
        }
        else
        {
            adj.css("transform: rotate(180deg)")
            dl.content("light code");
            light_theme = true;
        }
        href = themeHref(light_theme);
        _("#color-shema").attr("href", href);
    });

    dl.content("dark code");

    sections =_("#Sections");

    add_prvnext = function(pr,val ){
        tmp={};
        Object.defineProperty(tmp, pr, {value:val});
        prvnext.push(tmp);
        prvnextInd.push(pr);
    }

    createContent = function(rsp, to, req){
        data = rsp["content"];
        if(data)
        {
            prvnext=[];
            prvnextInd=[];
            for(item in data)
            {
                sections.create(item,{tag:"div"});
                par1={};
                par2={tag:"span"}
                for(ia in data[item])
                {
                    vd=data[item][ia];
                    if(__.o(vd))
                    {
                        el=sections.create(ia,
                        {
                            tag:"div",
                            class:"sub-ind"
                        }
                        );
                        for(ia2 in vd)
                        {
                            vd2=vd[ia2];
                            par2["data-url"]=vd2;
                            el.create(ia2,par2);
                            add_prvnext(ia2, vd2);
                        }
                    }
                    else
                    {
                        par2["data-url"]=vd;
                        sections.create(ia,par2);
                        add_prvnext(ia, vd);
                    }
                }
                sections.create(par1,par2);
            }
            _("#Sections span").click(goContent);

            //footer----------------------------
            footer = rsp["footer"];
            today = new Date();
            copyright = "&copy; ";
            copyright += today.getFullYear();
            copyright += " " + footer["copyright"];
            divFooter = _(".footer");
            divFooter.create(copyright, {tag:"span"});
            footerLinks = footer["links"];
            tmp = [];
            for(item in footerLinks) tmp.push(item);
            divFooter.create(tmp, {tag:"span", class:"link"});
            _(".link").click(goLfooter);
            soziale = footer["soziale"];
            for(item in soziale)
            {
                divFooter.create(1,
                {
                    tag:"a",
                    href:soziale[item],
                    class: item + " icon",
                    target:"_blank"
                });
            }
        }
        else
        {
            console.log(rsp);
        }
        //-----------------------------------
        key0=Object.keys(data)[0];
        key0_0 = Object.keys(data[key0])[0];
        H1 = key0_0;
        prvnextL = prvnext.length;
        goContent(data[key0][key0_0]);
    };

    var idc;

    viewDemo = function(){
        if(_(this).content()=="Try it")
        {
            _(this).content("Close");
            ids=_("#"+this.id.substr(1));
            html=ids.content();
            html = __.ins("<span.*?>(.*?)",html,"");
            html = __.ins("</span.*?>(.*?)",html,"");
            html = __.ins("&lt;",html,"<");
            html = __.ins("&gt;",html,">");
            html = __.ins("&amp;&amp;",html,"&&");
            html = __.ins("&amp;",html,"&");
            div =_(this).create(1,
            {
                add:"after",
                tag:"div",
                class:"RB",
                id:"_"+this.id
            });
            ifr = div.create(1,
            {
                tag:"iframe",
                allowfullscreen:"true",
                frameborder:"0"
            }
            );
            ifH=html.length<500?100:300;
            ifH+="px";
            ifrSt = "overflow:hidden;min-height:" + ifH;
            ifrSt += ";height:" + ifH;
            ifr.css(ifrSt);
            ifr.content(html);
            sy=this.offsetTop - 110;
            __.scroll(sy);
        }
        else
        {
            _(this).content("Try it");
            _("#_"+this.id).remove()
        }
    };
    //-------------------------------------------
    function getTitle(par){
            if(__.u(par)) _H1=H1;
            else _H1=prvnextInd[parseInt(par)];
            title_div_h1={};
            title_div="";
            if(__.ins("-",_H1))
            {
                title_div_h1.title = "Check type method "+_H1;
                title_div = "<div><i>res= __."+_H1.substr(0,1);
                title_div += "(Parameter)</i><br>";
            }
            else if(__.ins("(.\\ |\\.)",_H1))
                title_div_h1.title = _H1;
            else if(__.ins("^_",_H1))
            {
                title_div_h1.title = "Variable "+_H1;
                title_div="<div>";
            }
            else
                title_div_h1.title = "Method "+_H1;
            title_div_h1.h1 = "<h1>"+title_div_h1.title;
            title_div_h1.h1 += "</h1>"+title_div;
            return title_div_h1;
    }
    //--------------------------------------------
    function getTitleLinks(mt){
        stmt = mt?'style="margin-top:'+mt+'px"':"";
        stP = stR = stN = "";
        titleP = titleR = titleN = "";
        sth = 'style="visibility:hidden"';
        if(GET['indR'])
        {
            indR = GET['indR'];
            titleR=getTitle(indR).title;
        }
        else
        {
            stR = sth;
        }
        if(indP >= 0)
        {
            titleP=getTitle(indP).title;
        }
        else
        {
            stP = sth;
        }
        if(indN < prvnextL)
        {
            titleN=getTitle(indN).title;
        }
        else
        {
            stN = sth;
        }

        bl= '<div class="prvnext" '+ stmt +'>';
        bl+= '<div class="row">';

        bl+= '<div><p class="prev" '+stP+'>';
        bl+= '<i class="fas fa-arrow-alt-circle-left"></i> ';
        bl+= titleP +'</p></div>';

        bl+= '<div><p class="return" '+stR+'>';
        bl+= '<i class="fas fa-arrow-alt-circle-up"></i> ';
        bl+= titleR +'</p></div>';

        bl+= '<div><p class="next" '+stN+'>' + titleN;
        bl+= ' <i class="fas fa-arrow-alt-circle-right"></i>';
        bl+= '</p></div>';

        bl+='</div></div>';
        return bl;
    }
    //--------------------------------------------
    goRainbow=function(rsp,to,req){
        GET = __.url(1,req);
        if(code=GET['code'])
        {
            preff = '<div></div>';
            preff += '<pre><code data-language="';
            preff += code + '">';
            rsp = preff + rsp + '</code></pre>';
        }

        ["html","head","body"].forEach(function(tag)
        {
            rsp = __.ins("<"+tag+">",rsp,"&lt;"+tag+"&gt;");
            rsp = __.ins("</"+tag+">",rsp,"&lt;/"+tag+"&gt;");
        });
        //--------------------------------------------
        ind = H1ToInd();
        indP = ind - 1;
        indN = ind + 1;
        out=getTitle();
        h1=out['h1'];
        blPrvNextTop = getTitleLinks(-10);
        blPrvNextBottom = getTitleLinks();
        cont = blPrvNextTop + h1 + rsp + blPrvNextBottom;
        _(to).content(cont);
        //--------------------------------------------
        Rainbow.color();
        //--------------------------------------------
        Sc=_("#SectionsСontent code");
        if(Sc.ElL>0)
        {
            i=1;
            _("#SectionsСontent code").each(function(el)
            {
                el.attr("id","_"+i);
                i++;
            }
            );
        }
        SCbutton =_("#SectionsСontent > button");
        if(SCbutton.exists)
        {
            i=1;
            SCbutton.each(function(el)
            {
                if(el.content()=="0")
                {
                    el.hide();
                }
                else
                {
                    el.attr("id","__"+i);
                    el.content("Try it");
                }
                i++;
            }
            );
            SCbutton.click(viewDemo);
        }
        Sq=_("#SectionsСontent .quote");
        if(Sq.exists)
            Sq.each(function(el)
            {
                el.css("background-color:#f8f8f8")
            });

        //---------------------------------------
        Show = function(sel, set ){
        if(set)
            sel.each(function(el){el.show();});
        else
            sel.each(function(el){el.hide();});
        }
        //---------------------------------------
        function H1ToInd(){
        return parseInt(__.ins("^"+__.esc(H1)+"$",prvnextInd));
        }
        //---------------------------------------
        prev = _(".prev");
        retu = _(".return");
        next = _(".next");
        //---------------------------------------
        goContenPN=function()
        {
            cl=_(this).class();
            if(__.ins("return",cl))
                i = GET['indR'];
            else
                i = __.ins("prev",cl)?indP:indN;
            H1=prvnextInd[i];
            url=prvnext[i.toString()][H1];
            goContent(url);
        }
        //---------------------------------------
        mLink =_("a:not([href])");
        if(mLink.exists)
        {
            goLink=function()
            {
                iReturn=ind;
                H1=_(this).content();
                i = H1ToInd();
                url=prvnext[i][H1];
                url=__.url("indR="+ind, url);
                goContent(url);
            }
            mLink.click(goLink);
        }
        //--------------------------
        if(retu.exists)
        {
            retu.click(goContenPN);
        }
        prev.click(goContenPN);
        next.click(goContenPN);
    };

    goContent=function(u){
        if(__.s(u))
            url = u;
        else
        {
            el = _(this);
            url = el.attr("data-url");
            H1 = el.content();
        }
        url = "sections/" + url;
        __.send(
            {
                url:url,
                method:"get",
                to:"#SectionsСontent",
                func:goRainbow
            }
        );
        __.scroll(0);
    };

    changeThema = function()
    {
        href="themes/css/"+this.value+".css";
        _("#color-shema").attr("href", href);

    };
    thema=_("#thema");
    thema.create(getThemes());
    thema.change(changeThema);
    __.send(
    {
        url:"index.json",
        method:"get",
        responseType:"json",
        func:createContent
    }
    );
    bs =_("#block-setting");
    bsd =_("#block-setting div");
    ssh =_("#setting");
    dur="slow";
    bsd.hide(dur);
    bsd.attr("data-h","100px");
    bs.css("background-color:transparent");
    function showSetting(){
        bsd.show(dur);
        bs.class("RB BS",true);
        bs.css("background-color:white");
        ssh.class("fa-times",true);
        ssh.class("fa-cog",false);
    };

    function hideSetting(){
        bsd.hide(dur);
        bs.class("RB BS",false);
        bs.css("background-color:transparent");
        ssh.class("fa-cog",true);
        ssh.class("fa-times",false);
    };

    ssh.click(function(){
        if(bsd.ishide())
        {
            showSetting();
        }
        else
        {
            hideSetting();
        }
    });
    ssh.mouseenter(showSetting);

    getRandomString = function(ln) {
        var ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var result = '';
        chL = ch.length;
        for ( var i = 0; i < ln; i++ ) {
            result += ch.charAt(Math.floor(Math.random() * chL));
        }
        return result;
    };

    createCaptcha = function(ln){
        if(!__.n(ln)) ln=6;
        captcha =_("#captcha");
        captcha.content("");
        captcha.create(1,{tag:"canvas",id:"canv",width:130, height:50});
        canv = _("#canv");
        var ctx = canv.d.getContext("2d");
        ctx.fillStyle = '#f1f1f1';
        ctx.fillRect(0,0,130,50);
        captchaCode = getRandomString(ln);
        ctx.font = "35px HoneyScriptCYR-Light";
        ctx.strokeText(captchaCode, 10, 30);
        code.value("");
    };

    validationForm = function(){
        err = false;
        errS="background-color:#FFCCD9";
        re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(!re.test(String(email.value()).toLowerCase()))
        {
            err = true;
            email.css(errS);
        }

        if(!__.ins("\\S+",message.value()))
        {
            err = true;
            message.css(errS);
        }

        if((code.value()).toLowerCase() != captchaCode.toLowerCase())
        {
            err = true;
            createCaptcha();
            code.value("");
            code.css(errS);
        }
        return !err;
    };

    setWhiteBg = function(e){
        _(e.target).css("background-color:white");
    };

    sendForm = function(e){
        e.preventDefault();
        res = validationForm();
        if(res)
        {
            __.send({
            url:"Contact.php?senden=1",
            method:"post",
            to:"#modal1",
            func:(rsp, to)=>{
                _m = _(to);
                _m.modal(rsp);
                _m.modal(5)
            }
        });
        }
    };

    goLfooterFunc = function(rsp, to, req){
        _(to).modal(rsp);
        if(__.ins("Contact", req))
        {
            email = _("input[name='email']");
            message = _("textarea[name='message']");
            code = _("input[name='code']");
            createCaptcha();
            _(".contact a").click(createCaptcha);
            contactForm = _(".contact form");
            _(contactForm.d.elements).each((elm,ind)=>{
                if(ind<5) elm.click(setWhiteBg);
            });
            contactForm.submit(sendForm);
        }
    };

    goLfooter = function(){
        link = _(this).content();
        url = footerLinks[link];
        __.send({
            url:url,
            method:"get",
            to:"#modal1",
            func:goLfooterFunc
        });
    };
};
__.ready(start);

function themeHref(light_theme){
//defult light or dark theme
    theme=(light_theme)?"github":"obsidian";
    return "themes/css/"+theme+".css";
};
Enter fullscreen mode Exit fullscreen mode

index.json

{
"content":  
{
    "Preface":
    {
        "About CompactDOM tutorial":"AboutThisSite.html",   
        "What is the HTML DOM?":"WhatIsDOM.html",   
        "What is the CompactDOM?":"WhatIsCompactDOM.html",
        "How it works?":"HowItworks.html",
        "CompactDOM methods":"CompactDOMmethods.html",
        "Selectors of DOM elements":"SelectorsDOMelements.html"
    },

    "Events handler methods":{
        "on":"on.html",
        "blur":"blur.html",
        "change":"change.html",
        "childs":"childs.html",
        "click":"click.html",
        "dblclick":"dclick.html",
        "focus":"focus.html",
        "keydown":"keydown.html",
        "keypress":"keypress.html",
        "keyup":"keyup.html",
        "load":"load.html",
        "mouseenter":"mouseenter.html",
        "mouseleave":"mouseleave.html",
        "ready":"load.html",
        "resize":"resize.html",
        "scroll":"scroll.html",
        "submit":"submit.html"
    },

    "Basic methods":
    {
        "animate":"animate.html",
        "attr":"attribute.html",
        "attribute":"attribute.html",
        "checked":"checked.html",
        "class":"class.html",
        "content":"content.html",
        "create":"create.html",
        "css":"style.html",
        "display":"display.html",
        "childs":"childs.html",
        "each":"each.html",
        "hide":"hide.html",
        "ishide":"ishide.html",
        "link":"link.html",
        "lock":"lock.html",
        "modal":"modal.html",
        "position":"position.html",
        "prop":"prop.html",
        "reload":"reload.html",
        "script":"script.html",
        "selected":"selected.html",
        "show":"show.html",
        "style":"style.html",
        "tag":"tag.html",
        "transition":"animate.html",
        "val":"value.html",
        "value":"value.html",
        "send method":
        {
            "About the send method":"send1.html",
            "Redirect and submit":"send2.html",
            "POST XMLHttpRequest":"send3.html",
            "PUT XMLHttpRequest":"send4.html",
            "GET XMLHttpRequest":"send5.html",
            "DELETE XMLHttpRequest":"send6.html"
        }
    },

    "Auxiliary methods":
    {
        "ads":"ads.html",   
        "env":"env.html",
        "esc":"esc.html",
        "ins":"ins.html",
        "merge":"merge.html",
        "sid":"sid.html",
        "sob":"sob.html",
        "url":"url.html",
        "Arraybufer methods":
        {
            "setToArrBuf":"setToArrBuf.html",
            "getArrayType":"getArrayType.html",
            "getFromArrBuf":"getFromArrBuf.html",
            "setBlob":"setBlob.html"            
        },
        "Check type methods":
        {
            "a - array":"type.html",
            "b - boolean":"type.html",
            "f - function":"type.html",
            "n - number":"type.html",
            "o - object":"type.html",
            "s - string":"type.html",
            "u - undefined":"type.html"
        }
    },

    "Appendixs":
    {       
        "Codes for this site":
        {
            "index.html":"../index.html?code=html",
            "index.json":"../index.json?code=json",
            "index.js":"index_js.html",
            "index.css":"../css/index.css?code=css"
        },      
        "Files in examples":
        {
            "GetResponse.php":"GetResponse.html",
            "ViewResponse.php":"ViewResponse.html",
            "xml_document.xml":"xml_document.xml?code=xml",
            "html_document.html":"html_document.html?code=html",
            "content.css":"css/content.css?code=css",
            "content.json":"content.json?code=json",
            "content.txt":"content.txt?code=html"

        },
        "CSS":
        {
            "CSS for scroll method":"append3.html",
            "CSS for modal method":"append4.html"
        },
        "Predefined variables":"variable.html",
        "CompactDOM projects":
        {               
            "CaesarCipher.js":"Projects/CaesarCipher.js",
            "timeCalculator.js":"Projects/timeCalculator.js"
        }
    }
},
"footer":
{
    "copyright":"by Alto-Booking developer. All rights reserved.",
    "links":
    {
        "Imprint":"Imprint.html",
        "Contact":"Contact.php",
        "Privacy":"Privacy.html"
    },  
    "soziale":
    {
        "fab fa-github-square":"https://github.com/VladimirKheifets/Java-Script-library-CompactDOM",
        "fab fa-dev":"https://dev.to/vladimirkheifets/java-script-library-compactdom-4ji8",
        "fab fa-twitter-square":"https://github.com/VladimirKheifets/Java-Script-library-CompactDOM"
    }
}
}
Enter fullscreen mode Exit fullscreen mode

You can see several projects implemented with CompactDOM:
https://www.alto-booking.com/developer/timecalculator/

https://www.alto-booking.com/developer/caesarcipher/

Top comments (0)