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
  • #248685

    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;


    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.


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

      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;



    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; } 


    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; } 


    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)'),'');


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

    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);
        (now >= last + ms) ? exe(): time = setTimeout(exe, ms);



    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…


    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.


    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' : '';


    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.



    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:


    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.


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

    var root =,
    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…


    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, spot) {
          return, seat) {
            return aim[spot].reduce(function(sum, assay, clue) {
              return sum + assay*plan[clue][seat];
            }, 0);

    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.