working on it ...

Filters

snippets
125k
followers
280
Published by snip2code

Javascript

This channel collects useful snippets for Javascript language
Sort by

Found 125k snippets

    public by DinhoPutz modified Jan 30, 2019  131  2  2  1

    Exibir scrollbar (barra de rolagem) via console com JavaScript

    Algumas vezes, por algum erro de programação ou algum outro motivo qualquer a barra de rolagem pode desaparecer da página. Podemos testar se é isso mesmo via console com o código abaixo.
    //Exibir scrollbar (barra de rolagem) via console com JavaScript
    // Criar uma variável com elemento body
    var y =  document.querySelector("body");
    
    // Definir o estilo para exibir a scrollbar no elemento body
    y.style.overflow = "scroll !important";
    
    // Criticas e sugestões: @DinhoPutz																		

    public by DinhoPutz modified Oct 31, 2018  98  0  2  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 modified Sep 18, 2017  289  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 modified Sep 6, 2017  687  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 modified Aug 20, 2017  519  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 modified Aug 20, 2017  430  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 modified Aug 20, 2017  393  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 modified Aug 13, 2017  615  4  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 modified Jul 26, 2017  211  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 modified Jul 15, 2017  392  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