Make sure you’ve got a jQuery object

So, I’m writing a function that accepts jQuery DOM objects as arguments and sometimes even I forget that I’m supposed to pass a jQuery object when calling the function and pass only a selector. Here’s a short line of code that will make sure your function is working with a jQuery object:

$element = ($element.jquery) ? $element : $($element) ;

…or, if you’d rather check for falsiness and you don’t mind a single-line if statement maybe just…

if (!$element.jquery) $element = $($element) ;

Yes, it looks completely redundant and the else statement looks weird, but it’s totally cool, man. If you want to make sure your function doesn’t choke because some doofus (like me) forgot to wrap up the selector in $(), or maybe your element’s id has some weird characters in it and you need to pass the good ol’ document.getElementById('my_id') as your argument, it’s a tiny chunk of code for a whole bunch of insurance.

Here’s an example of this in action in a function that shows an alert when clicking a button element:

JavaScript:

function annoyingAlert($btn, msg){
    $btn = ($btn.jquery) ? $btn : $($btn) ;
    $btn.click(function(){
        alert(msg)
    }
}

HTML (and inline JavaScript):

<button id="this_button">Click Me</button>
<script type="text/javascript">
    annoyingAlert('#this_button', 'Good job genius, you clicked the button.');
</script>

Switching to WordPress.com for blog posts (from Tumblr)

Yes, I could set up my own WordPress blog and write my own theme and deal with the hassle of keeping the back end updated… But why? I’ve got a busy life and the most important thing to me right now is sharing what I’m working on and any cool tidbits I come across in the process. This free WordPress.com blog, which is maintained by the fine WordPress folks themselves, lets me insert code with the “code” shortcode (that’s code for putting code in my WordPress post “code” shortcode).

$(function(){
    $('body').append('<blink>Look how cool I am.</blink>');
});

These WordPress posts will be blasted over Teh Intarwebz to Twitter and Tumblr – so, if anyone even cares, you can follow me just about anywhere (except Facebook – why would I share this stuff on Facebook? I’ll stick to sharing my personal Instagram pics there). 😛

“601? What the Devil?”

The link here is where the “601” concept comes from (the original Andromeda Strain movie), and it pretty much describes modern life with the onslaught of information and data spewing from everywhere on the planet!

So, if you’re into web development, follow me for random musings on jQuery/Javascript, HTML, CSS, etc. I’ll try to keep the posts relevant to that, but there may be some random posts ones thrown in to see if anyone’s paying attention!