Normalizing addEventListener and event Between Modern Browsers and IE9

Modern browsers make using event listeners very easy. The API is normalized across all modern browsers (Chrome, Firefox, Safari, IE10+, iOS, Android), but if you’re stuck supporting IE9 on a project like I am right now, some elbow grease is needed to make your event listeners work the same across browsers.

Functions/Snippets For IE9

//Add an event listener to an element
function listen(element, event, callback) {
    if(element.attachEvent) {
        element.attachEvent("on" + event, function() {callback.call(element);});
    } else if(this.addEventListener) {
        element.addEventListener(event, callback, false);
    }
}

//If you prefer adding this function to the element prototype, use this syntax
Element.prototype.listen = function(event, callback) {
    if(this.attachEvent) {
        this.attachEvent("on" + event, function() {callback.call(this);});
    } else if(this.addEventListener) {
        this.addEventListener(event, callback, false);
    }
};

//Doing this allows you to add it to the NodeList prototype too
NodeList.prototype.listen = function(event, callback) {
    for(var i = 0, l = this.length; i < l; i++) {
        this[i].listen(event, callback);
    }
};

Inside the callback function, some more work needs to be done:

function callback(event) {
    //Get the event in both IE9 and modern browsers
    var event = event ? event : window.event;
    
    //Get the target of the event (in listeners like click)
    var target = event ? event.target : window.event.srcElement;
}

Finally, you can use the event to stop propagation using this function:

function stopPropagation(event) {
    if(event.stopPropagation) {
        event.stopPropagation();
    } else {
        event.returnValue = false;
    }
}

Calculating an Element’s Distance From the Top of the Document

For the times that I need to know how far an element is from the top of the DOM, not the top of it’s parent, I use this helper function.

//Loops through all parent nodes of an element to get it's distance from the top of the document
function getDistanceFromTop(element) {
    var yPos = 0;

    while(element) {
        yPos += (element.offsetTop);
        element = element.offsetParent;
    }

    return yPos;
}

This function returns the number of pixels the top of the element is from the top of the DOM.

Interviewing Recruiters

I get emails and messages from recruiters two or three times a week. On top of that, I help lead the local developer meetup, so I get contacted by recruiters to help introduce them to the appropriate developers for their open positions.

I don’t mind being contacted by recruiters, and if I can help them, I love to. I know enough developers that I can usually point them toward at least one prospect.

That said, I ask something in return. I’ve built a list of 11 questions that I ask them to answer before I pass the request on to developers in our community. Read More…

Wasted Moments, Missed Opportunities

You will only become yourself in the surrender to zero. Not zero things. Toys, people, friends, lovers, jobs, titles, commodities. A greater zero.

Zero moments wasted. On anything less than love, passion, dreams, suffering, nobility, greatness, wonder, grief, joy. Zero moments wasted. On anything less than what is incandescent, searing, unthinkable, laughable, hopeless, dangerously noble, impossible, daunting, unreasonably beautiful, senselessly noble.

Time isn’t wasting away. We are.

From Umair Haque’s essay, The Highest Score

My Thoughts on ‘Frozen’ Wrapped Up in One Perfect Sentence

I’ve watched the newest Disney movie, “Frozen”, about 1,000,000,000,000 times since it was released on DVD a month ago. I could never quite put into words my feelings about it. Luckily, Heather Armstrong put it perfectly:

…we, you and I, we deserve a cookie for not flinging whatever device they are using to watch that movie ONE MORE DAMN TIME out a two-story window, shrugging our shoulders and calmly explaining, “She did just tell me to let it go.”

So yeah. Being a parent comes with many amazing things, many awful things, and Frozen. #*@&!$(% Frozen…

More thoughts on Frozen later, but until then, hattip to Chris Ford for the link.

A Bad Rock…

Eric Meyer is living through my worst nightmare.

“Are you scared, Rebecca?”

A nod through tears, her jaw quivering again.

“Can you tell us what you’re scared of?”

She wept again, unable or unwilling to say the words. Kat and I choking on our pain and her pain as Rebecca sobbed with renewed terror, clinging to Kat and squeezing my hand in hers.

We asked her again, as gently as we could through our anguish. And again, later, when we had all recovered enough. And again.

Finally: “Baby, can you whisper it to one of us?”

She nodded, miserably.

“Who do you want to whisper it to?”

She pointed at Kat. Shifted her head up and around. Whispered, her voice so tiny and full of pain and fear and breaking into another wail: “Of dying.”

I will never know how long we wept with her. What we said to try to soothe her pain even a tiny bit. How we tried to comfort and protect her. I will always remember how utterly helpless and wounded and shattered I felt, the sick ache in the center of my chest.

After I read his post, I went to my 3 year old, hugged her tightly, and cried. She didn’t understand why I was crying. That’s OK. I didn’t want her to. She shouldn’t have to. She’s too young, but so are Eric’s daughters.

Absolute Positioning and Horizontal/Vertical Centering

Horizontal centering of an element is something that we, as web developers, do every day. It’s often an integral part of our designs. It’s easy with text and with relatively positioned block and inline-block elements. The problem arises when we try to center an element (horizontally or vertically) that is absolutely positioned. When I teased this post on Twitter, I received at least 10 replies saying that’s easy if you know the width of the child element. But that isn’t a limitation. Even if you don’t know the width, fear not! It’s actually really easy. *gasp* Read More…

Coding Music: The Hooten Hallers

Story time! When I spoke at OpenWest last summer, a friend and I were walking around downtown Provo and stumbled across a local establishment called ABG’s. There was a crowd overflowing out into the street, so being bored, we decided to see what was happening. We paid our cover charge, went in, and there was a live band playing. It was amazing, but as we left, I forgot to ask what the band’s name was.

Recalling the night six months later, I emailed ABG’s booking manager to see who was playing, and he introduced me to the Hooten Hallers. They’ve been in my regular rotation since and there’s little chance of them leaving it any time soon. They’re great to code to as their music blends into the background as you work. Read More…

Hooking Up to the window.onscroll Event Without Killing Your Performance

Waterfall and FPS chartThis week was my one-month anniversary at Lemonly, and in that month, I’ve used more onscroll event hooks than I have in the last 15 years of development, and for good reason. It’s a great way to add flair, track progress, or get parallax-y. If you don’t do it right, it’ll crush your site’s performance and irritate your users. So what’s the best way to hook up to the window.onscroll event and still maintain a reasonable frame-per-second rate when scrolling? Read More…

Looking Ahead (and Forward to) 2014

Edit: 9 out of 16. Not bad.

I’ve been really bad at setting goals for myself, so I am going to attempt to remedy that this year. This is a list of things I want to accomplish in 2014. I’m writing it down because I need it to serve as a list for myself, and as a way for all of you to hold me accountable. So hold me accountable, OK?

Personal

  1. Graduate College

    Sounds dumb, I know. I thought I had it done, but there was a class hanging out there after I switched catalogs that I didn’t know about. So one more semester and I’m done. I need to put it here because I didn’t try last semester. I’m basically incapable of giving a crap anymore.
    Success!

  2. Read to my daughter every night

    This one should be a no-brainer. I need to do it more.
    This one was difficult, as schedules often got in the way. But I need to do better in 2015.

  3. Read five fiction books

    Every book I read is either for a class, about programming, or non-fiction. I want to read (or listen to) more fiction.
    Success! If you include Audible, I read/listened to 31 fiction books this year.

  4. Beat Civilization 5 on King difficulty

    Such a dumb goal, but I’ve never beaten a Civilization game on harder-than-Prince difficulty. I want to change that.
    Ain’t nobody got time for that!

  5. Finish my basement

    It’s almost done. I’m paying someone to finish it, so I guess the goal should be “make enough money to pay someone to finish the basement”.
    Success! The last materials are on order, and will be installed in the next couple of weeks. I’ll count it.

  6. Take two vacations

    Real vacations… not “weekend in Minneapolis”. I want to see southern Florida and maybe Hawaii. I’d be happy with Bora Bora too, but I don’t have $25,000 sitting around.
    Success-ish. We spent 2+ weeks at my lake cabin this year because our daughter loves it.

  7. Eat at 25 new restaurants

    I eat too much pizza and not enough great, local cuisine.
    Success! I didn’t keep count, but if you include vacations, I crushed this.

  8. Shop responsibly

    Speaking of local, I think we all spend too much money on the Internet and at big box stores, and not enough at small, locally-owned businesses. Along with my money going to local restaurants (and not chains), it’s going to go to locally owned stores.

    I’m also going to give my money to stores that are socially responsible as well. Companies that care about their employees, the environment, and social justice will all see a much, MUCH larger portion of my money this year.
    Success! We spent far more money at locally-owned stores. I also almost avoided spending any money at Best Buy this year, which is a double success.

  9. Significantly improve my grilling abilities

    I made huge strides forward in 2013, and I want to continue the momentum this year. If you’re wondering, this is my bible.

    I’m also going to buy a slow cooker this year. Not sure which one, but brisket is in my near-future.
    Success! My wife thinks so, anyway.

  10. Attend four indie shows

    Odd one, but it’s been a couple of years since I’ve seen a good concert. I’d like to see 4 this year, with my wife. The Doomtree blowout in December counts as one. ;)
    Total failure. Only one show all year and it was Ed Sheeran. :(

  11. Start working out/losing weight

    Obligatory weight loss New Years resolution
    LOL. That’s all.

Professional

  1. Learn NodeJS

    I believe NodeJS is the immediate future of web development, so I am going to spend some serious time learning it. I’m helping start a Node meetup. I’ve got a stack of books that will teach me almost everything I need to know. I’ve found a support network that wants to learn with me. Now I’m searching for a good idea to build.
    Success! I’ve built two products with NodeJS. FileWrap, an agency file delivery app, and standing.io, a cool video player for conference videos.

  2. Speak at 10 conferences

    Between late 2012 and 2013, I spoke at over 20. That was too many. Cutting back this year means I’ll be able to spend more time with the family and on fun projects. I’m already scheduled to speak at Sunshine PHP, and I have submissions in to Midwest PHP, WordCamp Minneapolis, and a couple local events.
    Success! I spoke at 11, but will be limiting it even more this year.

  3. Write 26 blog posts

    I’m really bad at writing, but I want to write bi-weekly posts. I’m not sure I have the time, and this will be the first goal that gets dropped if I need time for others, but I’m putting it here because masochism.
    Total Failure. I have an idea to fix this, though. Stay tuned.

  4. Finish four premium 3themes themes

    Not to be forgotten (which I did at first), I want to finish 4 premium 3themes themes based off Spring theme, which means I also have to finish Spring theme. If you’re keeping score at home, that’s 5 professional, tested, debugged, completed, and good WordPress themes this year.
    Nope. 3themes was abandoned in favor of other ventures such as Prestige Conference.

  5. Build a profitable product for Lemonly

    This one is last, because I believe it will be the culmination of everything else on this list. It will be built with Node. It’s blog will be built on WordPress (based on a 3themes theme, of course!). It will be ranted about here and on Twitter. It will suck at first. But it will work, and it’ll get better. And it’ll make money.

    I have NO IDEA what it’ll be, but I have ideas…
    I built two great products, but like everyone who has built anything knows, monitization is hard.

So 2014 is already shaping up to be a busy year, but my real goal in 2014 is to spend more time with my family. I want to put puzzles together with my daughter. I want to go out to eat with my wife and have more of the long, deep, fun conversations that we have when we are together. It’s going to be an awesome year.

What are your goals for this year? What am I missing? Let me know what you’re doing this year in the comments or by tweeting me at @joshbroton.