Search code examples
javascriptjqueryjquery-uievent-propagation

Odd delays in jquery UI executions


I've been working on a section of a web app for a while. The javascript file has grown quite big, with a good chunk of it responsible for initializing and handling jQuery UI elements and events. To make things more readable and maintainable, I split off the UI initializers and event handlers to a separate file. This file is loaded before the logic file, as confirmed by the net tab of firebug.

Since I've split off the UI elements, I've noticed that the buttons and checkboxes have changed from single click triggers to double clicks before their event fires off for the first time. Afterwards, single clicks execute the events. To double check, I set a logging statement within the event handler and it doesn't print until the second click.

This is the script declaration of the html page

<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="../js/ajaxupload.3.5.js"></script>

<script type="text/javascript" src="../js/modernizer.js"></script>
<script type="text/javascript" src="../js/ui_initialization.js"></script>
<script type="text/javascript" src="../js/setCoordinates.js"></script>
<script type='text/javascript> 
  $(document).ready(function(){
    onload();
  });
<script type="text/javascript" src="../js/nav.js"></script>

onload is defined in setCoordinates, which in turn fires off setupElements in ui_initilization.

For example, I define a checkbox in html as

<div id='checkboxes'>
  <input type="checkbox" id="panel" class="checkbox"/>
  <label for="panel" id='paneLabel' class="checkbox"></label>
</div>

and handle the click event in ui_initilization.js as

$("#checkboxes").buttonset();
$("#paneLabel").text("Hide Panels");

$("#panel").click(function(){
  console.log("pane click");
  handlePanelButtonClick();
});

First click does nothing, and the logging statement doesn't show. Second click fires the event.

Is there a way to fix this?


Solution

  • Without live example it's really hard for me to solve this issue. Maybe it's some default browser behaviour ... Or the trigger of click isn't available on the first click

    Try this

    $("#panel").click(function(event){
        event.preventDefault();
        event.stopPropagation();
    
        //your code...
    });