working on it ...

Filters

snippets
126k
followers
281
Published by snip2code

Javascript

This channel collects useful snippets for Javascript language
Sort by

Found 126k snippets

    public by DinhoPutz  61  0  3  0

    Somar valores de um objeto no JavaScript

    Soma os campos de mesmo nome nos itens de um objeto
    var objeto = [
        { valor: 10 }, 
        { valor: 15 }
    ];
    
    objeto;
    
    var somaValores = function (novoObjeto) {
        // Aqui realiza a soma dos valores da propriedade "valor" dentro do objeto
        var total2 = novoObjeto.reduce((total, valor) => total + valor.valor, 0);
        // Resultado da soma 
        console.log( total2 );
    }
    somaValores(objeto);

    public by DinhoPutz  142  1  3  0

    Monitorar alterações em formulário, exibir alteração, filtro por campo.

    Objetivo: 1. Monitorar alterações apenas a parte do formulário contida dentro da DIV "divCheckList". 2. Monitorar alterações apenas os campos que contenham no atributo "for" a palavra (caracteres) "check_". 3. Exibir as alterações em tempo real dentro da div "#parcial".
    var selectElem = document.getElementById('divCheckList') // Seção onde se encontra o form, pode ser o ID da div acima dele ou de alguma div dentro do form.
    selectElem.addEventListener('change', function() {
        $("#parcial").html("");
        $("label").each(function(index, element) {
            var ele = $(element);
            var elementos2 = [];
            algo = ele.attr("for").indexOf("check_"); // aqui filtramos apenas os campos que conteam "check_" no atributo "for", poderia ser ID, Class, placesseholder...
            if (algo > -1) {
                variavel = ("#" + ele.attr("for"));
                elementos2 = [index, ele.html(), ele.attr("for"), $(variavel).val()];
                console.log(elementos2);
                $('#parcial').append("" + elementos2[1] + " - " + elementos2[3] + "\n");
            }                  
            else null;  
        });
    })
    

    public by teppeis  301  1  3  0

    Safari 10.1 `nomodule` support

    Safari 10.1 `nomodule` support: safari-nomodule.js
    /**
     * Safari 10.1 supports modules, but does not support the `nomodule` attribute - it will
     * load <script nomodule> anyway. This snippet solve this problem, but only for script
     * tags that load external code, e.g.: <script nomodule src="nomodule.js"></script>
     *
     * Again: this will **not** prevent inline script, e.g.:
     * <script nomodule>alert('no modules');</script>.
     *
     * This workaround is possible because Safari supports the non-standard 'beforeload' event.
     * This allows us to trap the module and nomodule load.
     *
     * Note also that `nomodule` is supported in later versions of Safari - it's just 10.1 that
     * omits this attribute.
     */
    (function() {
      var check = document.createElement('script');
      if (!('noModule' in check) && 'onbeforeload' in check) {
        var supportModule = false;
        document.addEventListener('beforeload', function(e) {
          if (e.target === check) {
            supportModule = true;
          } else if (e.target.hasAttribute('nomodule') && supportModule) {
            e.preventDefault();
          }
        }, true);
    
        check.type = 'module';
        check.src = '.';
        document.head.appendChild(check);
        check.remove();
      }
    }());
    
    

    public by szmerek  699  8  5  1

    OnClick without setting an attribute of the link

    //<div id="dog" >Woow woow</div>
    
    
        (function() {
            document.getElementById("dog").onclick = function() { 
                alert('fuf fuf'); 
            };
        })();																								

    public by szmerek  544  0  4  0

    Remove part of a string before specified character

    //remove string before '&' if want to include character '&' then 'indexOf("&") + 0'
    var str = "black&white";
    str = str.substring(str.indexOf("&") + 1);
    
    //or use regex
    var str = "black&white";
    str = /&(.+)/.exec(str)[1];
    
    // or use .split() and .pop() 
    var str = "black&white";
    str = str.split("&").pop();						

    public by szmerek  449  1  4  0

    Check whether a string matches a regex

    //RegExp allows to inject variable values into the regex string
    var str = "sample1";
    var re = new RegExp("^([a-z0-9]{5,})$");
    if (re.test(str)) {
        console.log("valid");
    } else {
        console.log("invalid");
    }					

    public by szmerek  414  0  5  0

    Hide element(s) by class

    Some examples for hiding the class.
    //Ex 
    //<div class="appBanner">appbanner</div> 
    
    document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
    
    //change the style rules of all elements matching the class
    
    [].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
      el.style.visibility = 'hidden';
    });
    
    //If for...of is available then use
    
    for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
    
    //And the other one
    
    Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });
    
    //and the last one
    
    var appBanners = document.getElementsByClassName('appBanner'), i;
    
    for (i = 0; i < appBanners.length; i += 1) {
        appBanners[i].style.display = 'none';
    }																								

    public by snip2code  656  3  4  0

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by AbhishekGhosh  235  0  3  0

    Adense-in-post

    Adense-in-post: Adense-in-post.js
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <!-- responsive_300x250 -->
    <ins class="adsbygoogle"
         style="display:block; text-align:center; width:100%;"
         data-ad-client="ca-pub-xxxxxxxxxxx"
         data-ad-slot="yyyyyyyyy"
         data-ad-format="rectangle"></ins>
    <script>
    (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
    
    

    public by ElectroSoft  401  0  5  0

    Prueba de Ajax

    Prueba de Axaj en javascript nativo.
    function ajax()
    {
        var elements = document.getElementsByClassName("formVal");
        var formData = new FormData(); 
        for(var i=0; i<elements.length; i++)
        {
            formData.append(elements[i].name, elements[i].value);
        }
        var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function()
            {
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                {
                    alert(xmlHttp.responseText);
                }
            }
            xmlHttp.open("post", "prueba.php"); 
            xmlHttp.send(formData); 
    }
    • Public Snippets
    • Channels Snippets