13

Favorite Code Snippets

over 9 years ago from , f-f-frontend @ lessonly.com

I know this is Designer News, but most of us code at least a bit. I was curious what your favorite bit of code is. Something cool, elegant, or otherwise. Show us the code, tell us the language, and tell us why you like it. :D

var arr = [1,3,5,4,7,2,8,5,4,77,34,5,6]; arr.sort( (a,b) => ((a==b) ? 0 : (a>b) ? 1 : -1) ); console.log(arr);

This is a beautiful bit of Javascript. It will only work in Firefox (for the time being), because of the little arrows. They basically equate to function(). This sorts an array in one line, which is pretty neat.

Can't wait to see everyone else's code!

Cheers, Conlin

11 comments

  • Colm TuiteColm Tuite, over 9 years ago (edited over 9 years ago )

    I'll get the ball rolling so. I wrote this function today for a project. It's a reusable function for changing link/span text. Rather than define what text to change to inside the javascript, I'm using data attrributes to make the code more reusable.

    $('.js-textEdit').click(function() {var oldText = $(this).text();var newText = $(this).data('text');$(this).text(newText).data('text', oldText);});

    <span class="js-textEdit" data-text="Show less">Show more</span>

    Here's a working example. http://jsfiddle.net/colmtuite/tRd79/

    6 points
  • Ahmet SulekAhmet Sulek, over 9 years ago (edited over 9 years ago )

    Detect clicks outside the target. Can work for the custom modals.

    $('body').bind('click', function(e) { if($(e.target).closest('#REPLACE_HERE').length == 0) { //outside of the box } });

    5 points
  • Andy LeverenzAndy Leverenz, over 9 years ago (edited over 9 years ago )

    Cool random color generator I'm using on my blog's re-design. Comes in handy for text or background colors that you want to be dynamic.

    $(function(){ $(".yourClass").each(function(){ var randomColor="rgb("+(Math.floor(57*Math.random())+100)+","+(Math.floor(57*Math.random())+100)+","+(Math.floor(57*Math.random())+100)+")"; $(this).css("color",randomColor) } )} );

    4 points
  • Clay MacTavishClay MacTavish, over 9 years ago (edited over 9 years ago )

    [CSS] Overlay psd on page for pixel perfect styling.

    .element { background: url("/images/about.png") no-repeat scroll 0 0 transparent; height: 1010px; left: 0; opacity: 0.5; position: absolute; top: 0; width: 1280px; z-index: 9999; }

    2 points
  • Removed AccountRemoved Account, over 9 years ago (edited over 9 years ago )

    document.write((new Date()).getFullYear());

    The most useful snippet ever. This code updates year automatically so it's perfect for site footers.

    1 point
  • Jonathan ShariatJonathan Shariat, over 9 years ago (edited over 9 years ago )

    I'm building a small plugin for Chrome and I needed to detect prices on a page. In turn I learned Regular Expression and I think they are awesome:

    \$[0-9]*,?.?\d{1,2}(.\d{1,2})?/ // regex for selecting prices

    Needs to cover:

    $1

    $12

    $12.99

    $12,000

    $12,000.99

    and NOT:

    $(jquery)

    $Words

    $10Billion Dollars

    1 point
  • Cihad TurhanCihad Turhan, over 9 years ago (edited over 9 years ago )

    If you want to represent a percentage as color(0%->red, 50->yellow, 100%->green) use this:

    function pct2hsl(min, max, value) { var percent = 100*(value - min)/(max - min); percent = percent > 100 ? 100 : percent; percent = percent < 0 ? 0 : percent; return "hsl(" + (200 - percent*1.9) + ", 80%, 50%)"; }

    example

    PS: For easiness hsl is used. İf you want to convert to rgb, I can provide it too


    The following is my favorite. It gives you which elements are added and removed from your array.

    Array.prototype.diff = function(that) { return { enter: $(that).not(this).get(), exit: $(this).not(that).get() }; };

    Example:

    var result = [0,1,2,3,4,5].diff([1,2,3,4,5,6,7]); // result will be {enter:[6,7], exit:[0]} // 6 and 7 are added, 0 is removed
    0 points
  • Jake ChapmanJake Chapman, over 9 years ago (edited over 9 years ago )

    /* Converts String number of seconds into 00:00 formatted time */ String.prototype.toTime = function () { var secNum = parseInt(this, 10); var hours = Math.floor(secNum / 3600); var minutes = Math.floor((secNum - (hours * 3600)) / 60); var seconds = secNum - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} var time = minutes+':'+seconds; return time;

    }

    var duration = '120'; console.log(duration.toTime()); // 02:00

    0 points