Solution 3

 
The third solution uses a nifty jQuery plugin called “Event filter”. Use it like this:
 
$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});
 
This filter can be found here: http://www.codenothing.com/archives/2009/event-filter/
 

Solution 4

 
The easiest solution to implement.
 
$(document).on('pagebeforeshow', '#index', function(){       
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more then once
        {
            alert('Clicked');
            e.handled = true;
        }
    }); 
});
 
Javascript is used to check if an event has already triggered. I don’t prefer this solution because it will not stop event binding process; it will just prevent multiple event executions.
 
Working Example 4
 
Note: Solution found here: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/
 
Here’s a code example if jsFiffle is unavailable:
 

HTML

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>    
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
            <a href="#second" class="ui-btn-right">Next</a>
        </div>

        <div data-role="content">
            <a data-role="button" id="test-button">Click me</a>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div> 
    <div data-role="page" id="second">
        <div data-theme="a" data-role="header">
            <h3>
                Second Page
            </h3>
            <a href="#index" class="ui-btn-left">Back</a>
        </div>

        <div data-role="content">

        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>    
</body>
</html>   
 

JavaScript

$(document).on('pagebeforeshow', '#index', function(){       
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more then once
        {
            alert('Clicked');
            event.handled = true;
        }
    }); 
});
 

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



  • Wow.. nice one.

    I’ve had this error before, don’t remember ho I handled it, but I know it was tricky.
    I even tried using the native javascript “onload” to wrap my jquery events, but It still happened anyway.

    This is a really good way to work around it.

    Thanks Dragan.

  • I tried solution 2 & it was perfect. I solved my problem.

    Thank you very much for this article.

  • Keven

    Solution 2 worked for great for me! Thank you!!

  • Kamil

    Thanks for this! I used second solution and it works great! Your post is a fantastic collction of useful solutions.

  • thank you very much, you save my day, i was looking the solution for my multiple firing problems, working great..

  • amine

    Very very useful. My day is saved. Thank you

  • Janou

    I used Solution #4 which was perfect for my needs. I couldn’t figure out for the life of me why my submit button within my partial view was executing twice. This solution solved my problem easy. Thanks!

  • Mayank

    Thanks For this ..this is really great..

  • Steve

    You are a hero!!!

  • Terence

    Excellent article. Saved my day even a year after you wrote it. Thanks

  • Terence

    Thanks for this nice article. Still saved my day even a year after you wrote it. thanks

  • Nice post

  • Carlos

    Jquery now has a solution for this. Similar to solution two.
    use :
    .one()
    http://api.jquery.com/one/

    • This is only a partial solution (thou still valid one). It is viable only if we don’t mind that handler is unbound after its first invocation.

  • Said Moshref

    Whats about $(“#button”).unbind(“click”).on(“click”,function(e){ return false));

    • off() should be used with on() :

      $(“#button”).off(“click”).on(“click”,function(e){ return false));

      Take from the official jQuery website:

      As of jQuery 1.7, use of .die() (and its complementary method, .live()) is not recommended. Instead, use .off() to remove event handlers bound with .on()

  • Thanks Man! Solution 2 worked for me! you have no idea how much time i wasted searching for a solution like this. Thanks alot man!

  • Chris

    What about event.stopImmediatePropagation()?

    From jquery site:

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

    Will this solve the problem?

    BTW very nice explanations!!

    • This will indeed work but in some cases and not always. That's why I didn't include it in this article.

  • Gytis Šk

    This is crazy. I am not even using standard DOM, I am triggering my own: $menu_item.trigger(‘menuclose’) and it still triggers twice. Gonna use e.handled solution. thx

  • Jacob

    Im usually making pages with a lot of refrehing divs and reloading stuff, so i have made my own simple solution which is handling all of my needs:
    $(‘myclass:not(.initialized)’).on(‘click’, function() { do something }).addClass(‘initialized’)
    then you can call your init functions all the time and not worry about multiple event bindings

    • Do you mind if I include this example as a possible solution?

  • Juan Carlos Alpizar Chinchilla

    While I’m working with the pagecontainer widget in jQuery Mobile 1.4.5, a have a pagebeforeshow event handled this way:

    $(document).on('pagecreate', function(event, ui){

    $(":mobile-pagecontainer").on('pagecontainerbeforeshow', function(event, ui){

    if (ui.toPage[0].id == 'target_specific_page'){

    console.log(ui);

    }

    });

    });

    $(document).on('pagecreate', '#specific_pages', function(){

    //stuff here

    });

    Which works but when I’m about to open the target page, it triggers the “pagecontainerbeforeshow” once per every page that was created before reaching the target page. For example if I had to navigate 4 times to get to the desired page, the console won’t show anything until I’m about to enter the desired page, but once the event triggers it logs 4 ui objects with the same info.

    Dragan Gaić Is there anything wrong with this implementation? The pagecontainer widget usage is still not clear enough for me. If there’s nothing wrong, considering I can’t use the ones that will trigger it only once, which is better between the off.on method and the event filter plugin in terms of performance?

  • Juan Carlos Alpizar Chinchilla

    While I’m working with the pagecontainer widget in jQuery Mobile 1.4.5, a have a pagebeforeshow event handled this way:

    $(document).on('pagecreate', function(event, ui){

    $(":mobile-pagecontainer").on('pagecontainerbeforeshow', function(event, ui){

    if (ui.toPage[0].id == 'target_specific_page'){

    console.log(ui);

    }

    });

    });

    $(document).on('pagecreate', '#specific_pages', function(){

    //stuff here

    });

    Which works but when I’m about to open the target page, it triggers the “pagecontainerbeforeshow” once per every page that was created before reaching the target page. For example if I had to navigate 4 times to get to the desired page, the console won’t show anything until I’m about to enter the desired page, but once the event triggers it logs 4 ui objects with the same info.

    @dragangai:disqus Is there anything wrong with this implementation? The pagecontainer widget usage is still not clear enough for me. If there’s nothing wrong, considering I can’t use the ones that will trigger it only once, which is better between the off.on method and the event filter plugin in terms of performance?

    • pagecontainer is still work in progress or at least it was. From what I can see at jQuery Mobile GitHub repository we’re talking about a dead framework. It’s no longer in development, at least since August. My advice, switch back to classic page events. I know they’re deprecated but its’ not like we’re going to see another jQuery Mobile version.

      • Juan Carlos Alpizar Chinchilla

        oh I knew it was slowing down but I didn’t know it was this bad 🙁 so there won’t be a jQuery Mobile 1.5 or the rumors about the jQuery UI fusion?

        I should also consider to move to another framework from now on; since my main usage was phonegap + jqm, do you consider react native a good option to move in?

        Thanks for the info 🙂

        • If you have a good Phonegap experience you should try Ionic + Cordova or if you still prefer jQuery then go with KenodUI + Cordova.

          On the other hand, React Native is a good choice, but you are somewhat limited. First, you’ll get a real native app but can only choose preexistent built in/3rd party components. You can’t modify them like you would with HTML5 and CSS. Second thing, unless nothing changed last 1-2 months you will be able to use it only on MacOS.

          • Juan Carlos Alpizar Chinchilla

            React is in rc for Linux and Windows so far as I’ve read but you’re right about the limitations it has, I think I’ll try with Ionic first. Are these performance wise better than jQuery Mobile? Thanks for your advice

          • I’m not a jQuery Mobile hater, but currently any other framework is faster than jQuery Mobile. Especially Ionic and OnsenUI. Though, if you mess up your code, it can became slower 🙂

    • Mechanical Man

      you are my savior.. just don’t know why it happens that way. THe 3rd one works fine for me

  • Georgi Iliev

    May the code be with you man, it’s my first true cross platform web application with tons of jquery and this “bug” was driving me crazy. Cheers

    • Georgi Iliev

      Maybe the fact that I bought a responsive theme has something to do with it, bu never the less, THANK YOU

      • You would stumble on this error sooner or later. It’s pain in the neck if you don’t know what’s happening.

  • Ramesh

    God bless you… You saved me from going crazy… If not for your post, i would have spent days to discover a solution.

  • CR Rollyson

    Would you use event.stopImmediatePropagation(); or no?

    • I would use it only if other solutions are not working. From my experience, stopImmediatePropagation() can bring more problems than help.

      • CR Rollyson

        Appreciate that answer. Mind elaborating on any issues you’ve had specifically with using stopImmediatePropagation() on a click event with button siblings as pagination elements?

        • I have an example that happend to me several days ago. I’m no longer using jQuerry but I was traying to fix something on a legacy software. For some reasons, dynamically generated buttons were triggering page refresh. Using stopImmediatePropagation on this event cause it to stop aworking all together.

  • khaled

    solution 4 is not working on jsfiidle

  • Luis Martín

    Hey!

    Your solution 4 is brilliiant!! It saved me a lot of testing and research.

    Thanks a lot!

  • nomadme

    To the solution 2 was the most elegant.

    Thank you.

  • Alessandro Bocci

    I’ve a similar problem on my project with jquery… using syntax like $( document ). on (“click”,”.class”, function(){ //dummy()}) each time page (or partial) reloads another handler is registered and event is fired many times. Anyway I’ve notice that using syntax like $(“.class”).click(function(){ something() }) when page or partial reloads only one event is fired. It’s just a stroke of luck or there’s a particular reason?