Sometimes “return false” is not enough; you need to prevent the event from bubbling up the DOM
Problem:
While implementing new Omniture calls on a client’s mobile site today, I noticed that two Omniture calls were being fired each time the new social media buttons I had added where clicked. These buttons only fired the Omniture call once, but each time one was clicked, two Ominiture calls were firing. I know this could not be the right behavior. The previous developer had implemented zepto.js, so I wanted to be sure it was not an anomaly of zepto that was causing the problem.
Short Answer:
Instead of ending each click handler with “return false”, I had to do end it with:
1 2 |
event.preventDefault(); event.stopPropagation(); |
Long Answer:
I noticed that when two Omniture calls were fired, they were not the same. One was the one I intended to call, and it was working perfectly. The other was more generic, and did not seem to understand what exatly was clicked. This led me to believe that there was a more generic event handler up the DOM somewhere, that was binding to any click, and firing off some general parameterss.
Yuck!
It turns out that someone had updated the Omniture library that was used, and they had bound a generic Omniture call to the anchor tag click event. Even though my click event returned false, the event bubbled up to wherever that generic event binding was. I found this StackOverflow post, and the answer provided was dead-on:
http://stackoverflow.com/questions/6207956/zepto-js-doesnt-return-false
So my click handler went from this:
1 2 3 4 5 6 |
$('#someElement').click(function(event){ //fire off Omniture Call omnitureFunction("some-value"); return false; }); |
…to this:
1 2 3 4 5 6 7 |
$('#someElement').click(function(event){ event.preventDefault(); event.stopPropagation(); //fire off Omniture Call omnitureFunction("some-value"); }); |
Summary:
I just needed to kill the event bubbling, and prevent the default behaviour, and everything worked just fine.