working on it ...

Filters

snippets
114k
followers
246
Published by snip2code

Javascript

This channel collects useful snippets for Javascript language
Sort by

Found 114k snippets

    public by szmerek modified Sep 6, 2017  172  2  4  0

    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  82  0  2  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  78  1  2  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  89  0  3  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  45  0  2  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 ElectroSoft modified Jul 15, 2017  124  0  4  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 by slavka1979 modified May 26, 2017  165  1  4  0

    Promise.all for Rejections and Resolves

    Always call then, even when one promise rejects
    // https://davidwalsh.name/promises-results
    Promise.all([
        // Resolves
        Promise.resolve(1), 
        // Rejects after 2 seconds
        new Promise((resolve, reject) => setTimeout(() => reject(1), 2000))
    ].map(p => p.catch(() => undefined))).then(() => console.log('done!'));

    public by vladimirov1 modified May 18, 2017  79  0  1  0

    print crosfilter results in console

    print crosfilter results in console: print_filter.js
    /**
     * Created by user on 18/05/17.
     */
    			// Super useful for debug in web console
    			function print_filter(filter){
    				var f=eval(filter);
    				if (typeof(f.length) != "undefined") {}else{}
    				if (typeof(f.top) != "undefined") {f=f.top(Infinity);}else{}
    				if (typeof(f.dimension) != "undefined") {f=f.dimension(function(d) { return "";}).top(Infinity);}else{}
    				console.log("DC DEBUG: "+filter+"("+f.length+") = "+JSON.stringify(f).replace("[","[\n\t").replace(/}\,/g,"},\n\t").replace("]","\n]"));
    			}
    
    

    public by JKCPR modified May 12, 2017  164  0  4  2

    is your DOM classy? Wouldn't your console like to know...

    Intended as Dev Tool to be utilised in the browser console so that refactoring your messy CSS can be less hurty.
    ;( 
      function (){
      "use strict";
    
      //get ALL DOM elements => BODY > *, BODY *
      var elms = document.body.getElementsByTagName("*"),
          i = elms.length,
          arr = [],
          classArray;
      
      //iterate, isolate, finally indicate
      while( i-- ) {
          classArray = elms[i].className.split(/\s+/);
          if (classArray.length > 1) {
              arr.push( classArray[1] );
          }
      }
      
      console.log( arr.join(',') );
      return arr;
      
    })();

    public by toledano modified Mar 6, 2017  223  0  4  0

    gulpfile.js para cmi_tema

    gulpfile.js para cmi_tema: gulpfile.js
    /**
     * Created by toledano on 06/11/15.
     */
    
    // inicializa gulp
    var gulp = require('gulp');
    
    // incluye los plugin
    var jshint = require('gulp-jshint');
    var concat = require('gulp-concat');
    var debug = require('gulp-strip-debug');
    var uglify = require('gulp-uglify');
    var sass = require('gulp-ruby-sass');
    var notify = require('gulp-notify');
    
    // Configuración
    var config = {
      sourcesDir: "./sources",
      sassPath:   "./sources/sass",
      nodeDir:    "./node_modules",
    }
    
    // tarea fontawesome
    gulp.task('icons', function() {
      gulp.src([
        config.nodeDir + '/font-awesome/fonts/**.*',
        config.nodeDir + '/bootstrap-sass/assets/fonts/**/*'
      ])
        .pipe(gulp.dest('./assets/fonts'));
    });
    
    // tarea bootstrap
    gulp.task('sass', function() {
      sass(config.sassPath + '/cmi.scss', {
        style: 'expanded',   // nested, expanded, compact, compressed
        loadPath: [
          config.sassPath,
          config.nodeDir + '/bootstrap-sass/assets/stylesheets',
          config.nodeDir + '/font-awesome/scss'
        ]
      })
      .on("error", notify.onError(function (error) {
        return "Equivocación: " + error.message;
      }))
      .pipe(gulp.dest('./assets/css'));
    });
    
    // Se define la tarea `scripts`
    gulp.task('scripts', function() {
      gulp.src([
        config.nodeDir    + '/jquery/dist/jquery.js',
        config.nodeDir    + '/bootstrap-sass/assets/javascripts/bootstrap.js',
        config.sourcesDir + '/js/**/*',
      ])
      // .pipe(jshint())
      // .pipe(jshint.reporter('default'))
      .pipe(concat('cmi.js'))
      .pipe(debug())
      .pipe(uglify())
      .pipe(gulp.dest('./assets/js/'));
    });
    
    // la tarea watch
    gulp.task('watch', function() {
      gulp.watch(config.sassPath + '/**/*.scss', ['sass']);
      gulp.watch(config.sourcesDir + '/**/*.js', ['scripts'])
    });
    
    // la tarea `default`
    gulp.task('default', ['scripts','icons', 'sass']);
    
    
                
    • Public Snippets
    • Channels Snippets