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 Oct 31, 2018  70  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  278  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  667  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  511  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  418  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  385  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  587  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 modified Jul 26, 2017  202  0  2  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  380  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 by rosskevin modified Jul 1, 2017  258  0  3  0

    material-ui NotificationCenter

    material-ui NotificationCenter: NotificationCenter.js
    // @flow
    
    import Queue from 'es-collections/Queue'
    import Snackbar from '@alienfast/material-ui/Snackbar'
    import PropTypes from 'prop-types'
    import React, {Component} from 'react'
    import Logger from './util/Logger'
    import Performance from './util/Performance'
    import Button from './Button'
    
    // if test, shorten duration for multiple messages - saves ~9 seconds on reset_password.feature
    const DefaultDuration = __TEST__ ? 750 : 3000
    
    type Props = {}
    
    type State = {
      queueSize: number,
      status: 'queueSizeChanged' | 'exited'
    }
    
    type Notification = {
      message: string,
      duration?: number,
      delay?: number,
      action?: string,
      onAction?: Function
    }
    
    const EmptyNotification = {
      message: ''
    }
    
    class NotificationCenter extends Component<void, Props, State> {
      static contextTypes = {
        eventBus: PropTypes.object.isRequired
      }
      props: Props
      state: State = {
        queueSize: 0,
        status: 'exited'
      }
      subscriptions: Array<EmitterSubscription>
      queue: Queue
      notification: ?Notification = EmptyNotification
    
      componentWillMount () {
        log.debug('componentWillMount')
        this.queue = new Queue()
        const { eventBus } = this.context
        // eventBus.registerEvent('NotificationCenter', 'notification')
        this.subscriptions = eventBus.subscribe('notification', this.handleNotification)
      }
    
      componentWillUnmount () {
        log.debug('componentWillUnmount')
        const { eventBus } = this.context
        eventBus.unsubscribe(this.subscriptions)
      }
    
      shouldComponentUpdate (nextProps: Props, nextState: State, nextContext: any) {
        //log.debug('shouldComponentUpdate', this.queue.size)
    
        // check to see if we are still showing the current notification
        const peek = this.queue.peek()
        //log.debug('compare notifications', this.notification === peek, this.notification, peek)
        if (this.notification === peek) {
          return false
        }
    
        return Performance.shouldComponentUpdate(this, nextProps, nextState, nextContext, true)
      }
    
      updateQueueSize () {
        this.setState({
          queueSize: this.queue.size,
          status: 'queueSizeChanged'
        })
      }
    
      handleNotification = (notification: Notification) => {
        const { delay } = notification
        const enqueue = () => {
          this.queue.enqueue(notification)
          log.debug('handleNotification', this.queue.size, notification)
          this.updateQueueSize()
        }
    
        if (delay) {
          setTimeout(enqueue, delay)
        } else {
          enqueue()
        }
      }
    
      handleRequestClose = (event: ?SyntheticUIEvent, reason: string, onAction?: Function) => {
        log.debug('handleRequestClose', reason, onAction, this.notification)
        const { duration } = (this.notification ? this.notification : {}) // wacky flow maybe type
        if (reason === 'clickaway' && !duration === 0) {  // allow clickaway on duration 0
          log.debug(reason)
        } else {
          if (onAction) {
            onAction()
          }
          this.queue.dequeue()
          this.updateQueueSize()
        }
      }
    
      handleExited = () => {
        log.debug('handleExited', this.notification)
        this.setState({ status: 'exited' })
      }
    
      render () {
        const { status } = this.state
        const size = this.queue.size
        let open
        let shownNotification: ?Notification
    
        if (size === 0) {
          // We must render the snackbar with an empty notification and close it so
          //  that we still achieve the ease out effect.
          shownNotification = this.notification
          this.notification = EmptyNotification
          open = false
        } else if (status === 'queueSizeChanged' && this.notification !== EmptyNotification) {
          // allow this message to exit
          shownNotification = this.notification
          open = false
        } else {
          // ready to display a new message from the queue
          shownNotification = this.notification = this.queue.peek()
          open = true
        }
    
        const { message, action: actionString, duration, onAction } = (shownNotification || {})
    
        // from the action string, create a button to trigger the action and dismiss the snackbar
        let action
        if (actionString) {
          action = [
            <Button
              key={actionString}
              color='accent'
              dense
              onClick={() => onAction ? onAction() : null}
            >
              {actionString}
            </Button>
          ]
        }
    
        const snackbarProps = {
          open,
          autoHideDuration: (duration === undefined ? DefaultDuration : duration)
        }
        log.debug('render Queue size:', size, ' status: ', status, message, snackbarProps)
    
        return (
          <Snackbar
            key={message}
            {...snackbarProps}
            action={action}
            onRequestClose={this.handleRequestClose}
            onExited={this.handleExited}
            SnackbarContentProps={{
              'aria-describedby': 'message-id'
            }}
            message={<span id='message-id'>{message}</span>}
          />
        )
      }
    }
    
    const log = Logger.get('NotificationCenter')
    
    log.debug('DefaultDuration', DefaultDuration, __TEST__)
    export default NotificationCenter
    
    
    
    • Public Snippets
    • Channels Snippets