jQuery on click is raised by text selection

So today I was building some basic toggle capabilities into a web page. Everything is working well, then I test selecting the text. Of course this causes the element to collapse on mouse up.

After some googling Stackoverflow of course had the answer…

$('h4').on('click', function() {
    if (getSelection() == "") {
        //do stuff

All it took was wrapping my code in a single if statement using getSelection().

Recent learns for Javascript / Web Development

File this in the unusual category, XHTML which likely all of us have used, never officially supported target=_blank for hyperlinks. XHTML Strict 1.0 – target=“_blank” not valid? is a more detailed discussion of this on StackOverflow. Ultimately it was only ever incorporated into the transitional specification. I just find it really ironic how something all of us take for granted wasn’t even in the official language specification.

Douglas Crockford knows how to troll. Straight from Code Conventions for the JavaScript Programming Language

Avoid conventions that demonstrate a lack of competence

Straight up says don’t do stuff just because it’s easier. Do stuff right. Or you suck.

Well said Crockford, well said.

At the bottom of his conventions I actually found out that JavaScript has a comma operator. I did a serious WTF when I read that. Of course it says to not use it. I did a little bit of digging to find out what is a comma operator Comma operator(,) Where it can “really” be useful.

Taking the best real world example from StackOverflow:

A Fibonacci generator:

for (
    var i=2, r=[0,1];
    r.push(r[i-1] + r[i-2]), i++
// 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377

That’s some crazy stuff there. It certainly looks cool at how you just 1 lined the Fibonacci sequence, but it certainly doesn’t add readability to code. I’m sure this is why Crockford advises against it.

Code that your first thought looking at it is #WTF does not belong in your codebase. The only exceptions to this are extreme performance optimized codeblocks that were deemed necessary by actual profiling. Optimizing without a profiler is the ultimate exercise in futility. You will most likely just make your application slower, harder to understand, and never touched the original problem.