css/jQuery/js snipplets

Forms

Highlight checked checkbox, radio button

           
           
<style> INPUT:checked + label {color: blue;} </style> <input id="theId" type="checkbox"><label for="theId"> The cat is here</label> or type='radio'
<style> INPUT[type="radio"]:checked {box-shadow: 0 0 0 3px blue;} </style> <style> INPUT[name="theRadioButtonsName"]:checked {box-shadow: 0 0 0 3px blue;} </style> <label><input type="radio" name="theRadio" class="radioSelected"> Highlight radio</label> <label><input type="checkbox" id="theCheckbox" class="radioSelected"> checkme</label>

Select apply selected option's class

        
        

        <select id="applySelectedClass">
            <option></option>
            <option class="red">Red</option>
            <option class="blue">Blue</option>
        </select>
        function selectApplySelectedClass(selector) {
            $(selector).each(function(){
                var e=$(this);
                if(!e.prop("multiple")) {
                    e.off("change",selectTextAddSelectedClass).on("change",selectTextAddSelectedClass);
                    var select = $(this), optionClass = select.children(":selected").prop("class");
                    select.removeClass(select.data("iaprevoptionclass")).addClass(optionClass).data("iaprevoptionclass", optionClass);
                }
            });
            function selectTextAddSelectedClass() {
                var select = $(this), optionClass = select.children(":selected").prop("class");
                select.removeClass(select.data("iaprevoptionclass")).addClass(optionClass).data("iaprevoptionclass", optionClass);
            }
        }
        jQuery(function($){ selectApplySelectedClass("#applySelectedClass"); });
        

Highlight label on input active

            
            
            <style> LABEL:focus-within{color:blue} </style>
            <label>Input focus <input type="text"> highlight its label</label>
        
<label for="inputId">Input focus highlights label, has for='inputId' </label><input id="inputId" type="text"> jQuery(function($){ $('LABEL[for]').each(function(){ $("#" + $(this).attr('for')) .focus(function(){ $("label[for='" + this.id + "']").addClass("labelFocus"); }) .blur(function() { $("label[for='" + this.id + "']").removeClass("labelFocus"); }) }); });

Highlight filled input

            
             
            <style> input.filled:not(:placeholder-shown) {background-color:yellow;} </style>
            <input placeholder=" " class="filled"  name="testFilled" type="text" value="" />
        

Radio button get or set selected value

        var valueSelected = $("input[name='radioName']:checked").val(); // if not found or all unchecked returns undefined
        $("input[name='radioName'][value='A']").prop('checked',true); // set to value A
    

Toggle password visibility

    function togglePasswordVisibility(id) {
        var x = document.getElementById(id);
        x.type = x.type === "password" ? "text" : "password";
    }
    

Prevent double submit

    .cursorWait{cursor:wait}
    .cursorWait:hover{cursor:wait}
    .cursorWait:active{cursor:wait}
    .cursorWait:focus{cursor:wait}

    jQuery(function($){ $("FORM").off('submit',iaDblSubmit).on('submit',iaDblSubmit); });

    /** diminish double submit occurrences */
    function iaDblSubmit() {
        // A.- All forms on page
        $("[type='submit'],[type='reset']").each(function(){$(this).attr('disabled','disabled').val(' ... ').addClass('cursorWait'); });
        // B.- Just the submitting form?
        //$(this).find("[type='submit'],[type='reset']").each(function(){$(this).attr('disabled','disabled').val(' ... ').addClass('cursorWait'); });
        $('BODY').addClass('cursorWait')
            .css({"pointer-events": "none", "user-select": "none"}); //@TODO timeout revert to pointer-events: auto,
            // -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
            //@TODO ver https://sdkcarlos.github.io/sites/holdon.html https://github.com/sdkcarlos/HoldOn.js
    }

    

Prevent back causing re-post

    try {history.replaceState({content: document.title}, document.title, document.location.href);} catch(e) {}
    

jQuery

On document ready

        jQuery(function($){

        });
    

ajax

Send json as a standard post or get query string

        $.ajax({
            url: '../backoffice/ajax/',
            method: 'GET',
            cache: false,
            processData: true, // en true pasa data (object) a ulr_encoded string, en false manda el object
            dataType: 'json',
            data: {},
        })
        .done(function(data, textStatus, jqXHR) {
            if(!data.status) {
                ia.alertError(data.message || "Error inesperado, intente más tarde.", "Error");
                console.log("ajax status wrong: " + this.url, data);
                return;
            }
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            ia.alertError(`Problemas al comunicarme con el server: <ul><lI>${errorThrown}<li>${textStatus}</ul>`, "Error", true);
            console.log('ajax failed: ' + this.url, arguments);
        })
        .always(function(data, textStatus, jqXHR) { //data|jqXHR, textStatus, jqXHR|errorThrown

        });
    

Send json as json object

        $.ajax({
            url: 'ajax/',
            method: 'GET',
            cache: false,
            processData: false, // en true pasa object a ulr_encoded string, en false manda el object
            dataType: 'json',
            data: {},
        })
        .done(function(data, textStatus, jqXHR) {

        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            ia.alertError(`Problemas al comunicarme con el server: <ul><lI>${errorThrown}<li>${textStatus}</ul>`, "Error", true);
            console.log('ajax failed', arguments);
        })
        .always(function(data, textStatus, jqXHR) { //data|jqXHR, textStatus, jqXHR|errorThrown

        });
    

js

Snipplets

isLocalhost

    const isLocalhost = Boolean(
      window.location.hostname === 'localhost' ||
        // [::1] is the IPv6 localhost address.
        window.location.hostname === '[::1]' ||
        // 127.0.0.1/8 is considered localhost for IPv4.
        window.location.hostname.match(
          /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
        )
    );
    

document.cookie string to object

    document.cookie.split(";").reduce((acc, cookieStr) => {
      let cookieArr = cookieStr.split("=", 2).map((val) => val.trim());
      acc[cookieArr[0]] = cookieArr[1];
      return acc;
    }, {})
    

Get windows dimensions

    function getWindowDimensions() {
        var doc = document, w = window;
        var docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat') ? doc.documentElement: doc.body;
        var width = docEl.clientWidth;
        var height = docEl.clientHeight;
        // mobile zoomed in?
        if ( w.innerWidth && width > w.innerWidth ) {
            width = w.innerWidth;
            height = w.innerHeight;
        }
        return {width: width, height: height};
    }
    

strim, Super Trim

    // Convert all consecutive spaces, tabs, cr, lf to one space
    function strim(s) { return s.replace(/(\p{Z}+)|(\s+)/gmu,' ').trim(); }
    

Date helpers

    function getFistDayOfMonth(d){ return new Date(d.getFullYear(), d.getMonth(), 1); }
    function getLastDayOfMonth(d){ return new Date(d.getFullYear(), d.getMonth() + 1, 0); }
    function getMondayOfWeek(d){ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + (d.getDay() === 0 ? -6 : 1) - d.getDay()); }
    function getSundayOfWeek(d){ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + (d.getDay() === 0 ? 0 : 7) - d.getDay()); }
    

CSS

Cheat sheet

Selectors

        ? check
                
.classhas class
.class1.class2has both class1 and class2
#idwith id='id'
imgall img elements
*all elements
Descendants
.class1 .class2class2 that is a descendant of an element with class1
div, pall div and all p elements
div > pall p elements where the parent is a div element
div + pall p elements that are placed immediately after div elements
p ~ ulall ul element that are preceded by a p element
Attribute
[attribute]has attribute, ie: name
[attribute=value]attribute's value is exactly equal value
[attribute*=value]attribute's value contains the substring value
[attribute~=value]attribute whose value is a whitespace-separated list of words, one of which is exactly value
[attribute^=value]attribute's value begins with value
[attribute|=value]attribute whose value can be exactly value or can begin with value immediately followed by a hyphen, -
[attribute$=value]attribute's value ends the value
Modifiers
Tag a
:link, :active, :visited, :hover
:target#news:target Selects the current active #news element (clicked on a URL containing that anchor name)
Tag input
:enabled, :disabled
:indeterminate
:optional, :required
:invalid, :valid
:in-range, :out-of-range
::placeholder
:placeholder-shown
:read-only
:default
:focus
:checked
::selection
Text
::first-letter ::last-letter ::nth-letter ::nth-last-letter? check
::first-word ::last-word ::nth-word ::nth-last-word
::first-line ::last-line ::nth-line::nth-last-line? check
Descendants
:first-child, :last-childtd>
:first-of-type, :last-of-type
:nth-child(n)
:nth-last-child(n)
:nth-last-of-type(n)
:nth-of-type(n)
:only-of-type
:only-child
WIP work in progress...
:not(selector)
::after, ::before
:root
:emptyp:empty every p element that has no children
:fullscreen
:lang(language)

Links

        
    

versión: 1.0.2 2020-10-11

How to: add an entry / snipplet


    <H#>Título</H#>
    <div class="collection">
    <pre>
        contenido
    </pre>
    </div>

    
Pegar en el lugar donde se desea que salga cambiando el h# por el que le toca, por ejemplo H3, del 2 al 6.
Nota: El Índice (ToC) se genera automáticamente.