Для получения полного доступа
зарегистрируйтесь.

Section:
Sub-section::
Languages:


Gravatar image
creocoder
  • Reputation: 3
  • Snippets: 1
  • Revisions: 0
    var loader = function () {
        var url = $('meta[name="api-base-url"]').attr('content') + 'projects';
        var xhr;

        return function (args) {
            args = $.extend({ refresh: false }, args);

            if (args.refresh) {
                url = $('meta[name="api-base-url"]').attr('content') + 'projects';
            }

            if (url && (!xhr || xhr.readyState === 4)) {
                xhr = $.get(url, function (data) {
                    if (args.refresh) {
                        $projects.find('tbody').html(projectsTemplate(data));
                    } else {
                        url = (((data || {})._links || {}).next || {}).href;
                        $projects.find('tbody').append(projectsTemplate(data));
                    }
                });
            }
        };
    }();

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Thanks to closures we can avoid using global flag which spoils the scope.

The code could be executed in any browser console. To trigger it, click anywhere on the page.

window.addEventListener('click', function () {
    var i = 0;
    return function () {
        window.alert('You\'ve clicked it ' + (++i) + ' time(s).');
    };
}());
IStranger
  • Reputation: 17
  • Snippets: 8
  • Revisions: 0

Often we need remove CSS classes that begin with certain string. For example: has-state-active, has-state-pending, has-state-disabled. Easiest way is to use wildcards: has-state-*.

Following function supports them (requires jQuery):

/**
 * Removes CSS classes of element using wildcards:
 *
 * @example
 * <code><pre>
 *
 *          // create some element
 *      var $element = $('<div id="#some-element"/>')
 *                          .addClass('base-class has-state-active item item-75')
 *                          .appendTo('body');
 *
 *          // remove classes with few prefixes
 *      removeClassWildcard( $element, 'has-state-* item-*');
 *
 *          // display element classes
 *      console.log($element.attr('class'));    // >> "base-class item"
 *
 * </pre></code>
 *
 * @param {jQuery|*}    $element
 * @param {String}      removals        Classes to delete, for example: 'foo-* bar-*'
 * @returns {jQuery|*}                  Passed element
 */
function removeClassWildcard($element, removals) {
    if (removals.indexOf('*') === -1) {
        // Use native jQuery methods if there is no wildcard matching
        $element.removeClass(removals);
        return $element;
    }

    var patt = new RegExp('\\s' +
            removals.replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s') +
            '\\s', 'g');

    $element.each(function (i, it) {
        var cn = ' ' + it.className + ' ';
        while (patt.test(cn)) {
            cn = cn.replace(patt, ' ');
        }
        it.className = $.trim(cn);
    });

    return $element;
}

Example:


  // create some element
var $element = $('<div id="#some-element"/>')
                  .addClass('base-class has-state-active item item-75')
                  .appendTo('body');

  // remove classes with few prefixes
removeClassWildcard( $element, 'has-state-* item-*');

  // display element classes
console.log($element.attr('class'));    // >> "base-class item"
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Safari and old Chrome are triggering additional popstate event on page load. Modern Chrome fixed it but it still happens in current Safari.

The idea is to register a handler after initial popstate pops. It is triggered on load so we're adding handler for it. setTimeout with 0 delay is to make sure handler registered last.

$(window).load(function() {
    setTimeout(function() {
        $(window).on('popstate', function (e) {
                // handle it
        });
    }, 0);
});
IStranger
  • Reputation: 17
  • Snippets: 8
  • Revisions: 0

"Golden" rule of frontend optimization often recommends to insert all JS scripts on page end. However usualy we can't remove <script src="//jquery.js"> from page <head>, because page content can contain many onReady-handlers, for example $(function(){ ... }).

This short snippet allows move jquery.js from <head> to end of <body> without changing onReady-handlers.

Snippet:

<head>
	<script>
		// Fallback code for the jQuery inline scripts on pages:
      if (window.jQuery === undefined) {
          window.jQueryReadyHandlers = [];

          window.$ = window.jQuery = function (callback) {
              window.jQueryReadyHandlers.push(callback);
              return window.$;
          };

          window.$.ready = window.$;
      }
  	</script>
    <!-- ...some head items -->
</head>
<body>

	<!-- ...some page content -->
    
    <script> 
    	// some onReady-handlers
      $(function(){
          console.log('First callback');
      });

      jQuery(document).ready(function(){
          console.log('Second callback');
      });
    </script>
    
    <!-- ...some page content -->


	<script src="//js/jquery.min.js"></script>
    <script>
    	jQuery(window).load(function(){
        	if(window.jQueryReadyHandlers) { 
            	$.each(window.jQueryReadyHandlers, function(index,func){  
                	$(func);
                });
            }
        });
    </script>
</body>