CodeBasket Code collection
Snowy background with canvas

Wintertime, usually that time of year when snow is appearing on websites here and there.

Many of them use the terrible jQuery.animate(), performance-wise a catastrophical choice.
A particularly used solution was so terrible in IE, it breaks the entire display of the website, hogs 100% GPU, spikes at roughly 75% CPU and includes occasional flickering of the website. Firefox is a bit laggy, Chrome no issues.
Sadly, IE still has to be supported on many coporate websites and this snowy theme is always an issue.

Curiously, IE has no issues with canvas rendering, though.
So, how about a reusable snow effect for canvas?

This JavaScript snippet is based on this Codepen.

Show
Aliasing jQuery selectors

While jQuery has been important at advancing the capabilities of JavaScript, it's most useful thing is its selector flexibility.
Doing a simple $('.sel .complex > .nested ~ .element').length is just too good.

But just to use those we won't need to pull in jQuery.
We can simply alias this function to $ and tweak it a bit.
Personally I always thought it's an odd thing to get all matching elements back and not just one.

The browser compatibility is pretty great for this solution as well.
Just as always, the IE in version 8 and below doesn't exactly play ball and only supports CSS 2.1 selectors and four CSS3 ones.
But who supports IE8 anymore? Poor souls...

Show
Dynamic bulk creation of (nested) elements

Recently I am re-doing a very old project of mine, where I try to use as much plain JavaScript as possible.
Main reason is to keep dependencies at a healthy minimum and to utilize new ES features with Babel, as well as for the fun itself. There's really no need for jQuery whatsoever these days anymore.

Even if plain JavaScript has improved immensely since I started with it, there's still one main disadvantage. You have to write a lot of code for simple tasks. To speed things up you have to write quite a few little helpers, with the side effect of making your code more readable.

For instance, that's the reason why I aliased $ and $$ for document.querySelector(All).
In my project there's not that much JS necessary, but there's still a lot of createElement here and there, appending childs to parents and stuff. So I end up with a lot of similar code.
Basically plain JS leads to DRY violations (if you don't pay attention).

Hence I quickly hacked together a simple solution to create nested elements in a recursive manner, returning the complete block of elements.
There could be a bit more error handling, but it fulfills its needs.

It works like this: you insert an Array of elements you want to have created.
Example: [ 'div', 'h1', 'span', ... ]
This would create each element and append it to the previous, if there is no previous element that's the parent (here that's the div).

Now, that's not quite helpful, what's with innerHTML? And how do we separate the information of what exactly is the element and what the innerHTML?
Easy, instead of a string naming the element, we can use a JSON representation and alias the element to create with an underscore and the innerHTML with two underscores.
Example: [ 'div', { '_': 'h1', '__': 'This is a header' }, { '_': 'span', '__': 'Some span content' }, ... ]

Great, but what about all other attributes, like class, custom data attributes?
Easy, we just add it to the JSON literal as is.
Example: [ 'div', { '_': 'h1', '__': 'This is a header', 'class': 'header' }, { '_': 'span', '__': 'Some span content', 'data-test': 'test-attribute' }, ... ]

Cool, but what was that about nesting?
Simple, use a subarray, if the function finds an array instead of a string of JSON object, it calls itself with that array again, creating the whole subarray, return the created elements and append that to a previous element.
Example: [ 'div', { '_' : 'h1', '__': 'Example Elements' }, [ { '_': 'h3', '__': 'Subheader' }, { '_': 'small', '__': 'Something small on the side', 'class': 'pull-right' } ]

Show
Input AutoCompletion

There are countless JavaScript plugins out there, providing you with the ability to create an autocomplete input. One has this incredible killer-feature you didn't know you want but is way too strict in how you can use it. The other has no outstanding feature and somehow works but is actually older than Web 2.0. Yet another depends on jQuery UI that you desperately want to remove but don't know how.
Well, basically one is worse than the other.

This feature is so commonly used, but what exactly would you need to accomplish autocompletion? Preferably one that is capable of AJAX? Let's see in this quick and dirty attempt.

This website has no builtin AJAX responses, so we're gonna fake that part, though. (There's always a catch with autocompletion, eh?)

Show
Selecting elements with arrow keys

There are probably a lot of different ways to approach this. Simply grab all elements of a certain type and iterate no matter what, use all elements only in a certain container and iterate no matter what.

Or like in this snippet: select all elements with a specific class and make them accessible with the arrow keys by checking the y-position of the elements, but also support a dynamic threshold for those elements that may not be entirely on the same y-position but should be considered as such. Pretty simple, yet effective.

Start with hitting right or down arrow key. There's support for windows resize as well.

However, if there is a blocker in between the elements you want to move around, this snippet doesn't particular know about those, so it ignores them and sets the active tile right or left from it. This is just to showcase a certain possibility to ignore elements.

To move from row Y to row Y+1 with column x, when on that column is a blocker, it would probably be best to go a row deeper as long as possible until a non-blocker element is found (if there are any) in opposite to what this snippet does. Yet again, there are several ways to approach this. :)

Show
Dynamically set a Timer on any event, enable do-overs, even add cancel events

There's this common task to fire an event when a user hovers the mouse over a certain element. Easily done, right?

But then there's this particular change request to fire the event with a certain delay. Like zoom in on an image, or open a tooltip, or a popup with more information only if a certain amount of time passed and only if the user does not move the mouse away or fires another particular event.

Nothing too complicated for sure, but isn't there a more general, reusable way of dealing with something like this? Hm...

Show
Animation: Counting up in container

This snippet is the attempt at a rather high-performance counter, still with some dynamic settings for each tile.

Instead of using a lot of DOM element deletions/creations, certain tiles are re-used by only changing the content. To keep the document element selection (and therefore traversing) at a minimum as well, references to the elements are saved and used later on. This gives a little performance boost at the cost of more memory usage.

This solution is purely plain JavaScript.

Show
Sorting a table by thead column click

How to sort small to medium tables quickly? That's pretty hard. Because sorting has always performance implications. But so does DOM manipulation for a lot of elements.

So, what is better? Changing row * columns innerHTML content, or detaching and re-attaching the DOM rows in the desired order? Doing the sorting just in time, or ahead of time?

This snippet uses an AOT approach by faking a sort on all columns and saving the row's position for a column x sorting, ascending and descending. The result is saved on the tr itself as classes. If a user clicks the thead column, the algorithm checks the corresponding class on the trs, sorts the DOM row elements accordingly and (re-)attaches them to the table.

Improvements might most likely possible in how the table is changed and saving some intermediate steps. But that's perhaps for another snippet.

Show

About Privacy Enable JS
Login