Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Your best snippets

  • This topic is empty.
Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #248685
    Shikkediel
    Participant

    Doesn’t have to be by your own hand of course, as long as it clean and nifty. This one is though, a feature test for animation/keyframes support:

    function stepAnimation() {
    
        var pattern = new RegExp('KEYFRAMES');
    
        for (var bit in CSSRule) {
        if (pattern.test(bit)) return true;
        }
    }
    

    Usage:

    if (stepAnimation()) { // do stuff with keyframes }
    

    More to follow but I’ll give each it’s own post, if they’re worth it…

    Comments or suggested improvements always welcome!

    Edit – already noticed some minor improvements myself, lol.

    #248705
    bearhead
    Participant

    if you want to use something other than a period after the numbers in an ordered list:

    ol{
      list-style-type: none;
      margin-left: 0;
    }
    ol li {
      counter-increment: customlistcounter;
    }
    ol li:before {
      content: counter(customlistcounter) "YOUR SYMBOL";
      float: left;
      width: 1.5em;
    }
    li:first-of-type {
      counter-reset: customlistcounter;
    }
    

    example:
    http://codepen.io/kvana/pen/JGyQNQ

    #248706
    Beverleyh
    Participant

    Here are my faves for class management in plain JS;

    Check for existence of a class;

    function hasClass(el, cls){
        if (el.className.match('(?:^|\\s)'+cls+'(?!\\S)')) { return true; } 
        }
    

    Usage

    var myelement = document.getElementById('myelement');
    if (hasClass(myelement, 'class-to-check-for')) {
        // do something
        }
    

    Add a class;

    function addClass(el, cls){
        if (!el.className.match('(?:^|\\s)'+cls+'(?!\\S)')){ el.className += ' '+cls; } 
        }
    

    Usage

    var myelement = document.getElementById('myelement');
    addClass(myelement, 'class-to-add');
    

    Deleted a class;

    function delClass(el, cls){
        el.className = el.className.replace(new RegExp('(?:^|\\s)'+cls+'(?!\\S)'),'');
        }
    

    Usage

    var myelement = document.getElementById('myelement');
    delClass(myelement, 'class-to-delete');
    
    #248723
    Shikkediel
    Participant

    Those are great, thanks for the feedback. :-)

    The counter-increment property is definitely a hidden gem. And those regular expression will turn out to be very handy.

    Here’s another nice snippet, for throttling functions – taken from a demo page of Beverley:

    function throttle(fn, ms) {
      var time, last = 0;
      return function() {
        var a = arguments, t = this, now = +(new Date),
        exe = function() {
          last = now;
          fn.apply(t, a);
        };
        clearTimeout(time);
        (now >= last + ms) ? exe(): time = setTimeout(exe, ms);
      }
    }
    

    Author

    Usage:

    throttle(someFunction, 100)
    

    This will limit the function inside to be executed only once every 100ms. Can be very handy to restrict overenthustiastic code execution based on scroll of resize events for example.

    window.addEventListener('resize', throttle(someFunction, 100));
    

    From what I can see, it also includes some code for debouncing. That will make sure the function is executed once more afterwards. Otherwise one might “miss out” on an event that happened 99ms into keeping track…

    codepen.io/anon/pen/xRjEqw

    #248731
    bearhead
    Participant

    Return a number 1-n with javascript:

    number = Math.floor((Math.random() * n) + 1);
    

    n can be any number, so if you wanted to simulate a 6-sided die roll, it would be a 6.
    Pretty basic, but I use it all the time.

    #248734
    Shikkediel
    Participant

    Let me give that a virtual thumbs up for neatness, as to not clutter the thread with green banners. And then add this feature test for transition support I’ve recently fiddled together. It will also select the correct event to use for transitionend.

    var pulse = 'TransitionEvent' in window ? 'transitionend' : 'WebKitTransitionEvent' in window ? 'webkitTransitionEnd' : '';
    

    Usage:

    if (pulse) {
    
    target.addEventListener(pulse, function() {
    
        // do stuff on transitionend
    });
    });
    }
    

    Slideshow demo

    I think it’s valid to use these days but slightly discriminates against early versions of Opera.

    #248761
    Shikkediel
    Participant

    Edited…

    This one supposedly has an issue with Safari and private browsing mode – may need an update.

    Having done a search across the net and not really liking any of the answers here much because accessing storage to check it’s presence just doesn’t seems like the right approach, I tested and made another snippet that checks the availability of web storage but still detects whether it happens to be disabled.

    Based on this article:

    Link

    var depot = (function() {
      try {
      return localStorage;
      }
      catch(e) {}
    })();
    

    Besides having a variable that can be used inside an if statement as a possible falsy, storage itself will also be cached and usable.

    if (depot) {
      depot.setItem ...
    }
    

    Another thing about the mostly accepted approach that Modernizr also uses is that Mozilla docs state that localStorage is synchronous in nature. This can block rendering of the main document unless you wait for it to be ready. With the above snippet, there’s no need to be concerned about that either.

    #248799
    Shikkediel
    Participant

    Another feature test – for full support of the most modern flexbox syntax (excluding buggy IE10):

    var root = document.documentElement.style,
    flexsupport = 'flexWrap' in root || 'WebkitFlexWrap' in root;
    

    I did not mean to limit the topic to JS by the way. Anything that qualifies as clean and nifty will do.

    :-)

    And I thought I’d mark bearhead’s second contribution after all but there seems to be a time limit on that…

    #284346
    Shikkediel
    Participant

    I had a hard time finding a good function to multiply two multidimensional arrays (no point in using math.js for just that method only) so I cherry picked some snippets from the web and combined them into a tiny jQuery plugin:

    (function($) {
    
      $.multiply = function(aim, plan) {
    
        // creates empty array to hold values
    
        var vector = Array.apply(null, Array(aim.length)).map(function() {
          return Array.apply(null, Array(plan.length));
        });
    
        // multiplication
    
        return vector.map(function(peg, spot) {
          return peg.map(function(dab, seat) {
            return aim[spot].reduce(function(sum, assay, clue) {
              return sum + assay*plan[clue][seat];
            }, 0);
          });
        });
      }
    })(jQuery);
    

    If you have two matrices likes this (size is accounted for as long as compatible for multiplication), with dimensions typical to describe 3d transforms:

    var matrix1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],
    matrix2 = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
    

    They can be multiplied in this way:

    var mymatrix = $.multiply(matrix1, matrix2);
    
Viewing 9 posts - 1 through 9 (of 9 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.