jqueryjquery-ui-accordion

jQuery first click ignored?


I have this piece of code used with jQuery UI

function ViewClient(RelationID) {
    console.log('entering');
    $('a[id^="contact_show"]').on('click', function (e) {
        console.log('clicking '+RelationID);
        ShowClientInfo(RelationID);
        $('#accordion').accordion({active: 2});
    });
}

The link the user clicks to do the action looks like this (and resides on panel 1 of the accordion):

<a href="#" id="contact_show_204" onclick="ViewClient(204);">View Client</a>

This should then close panel 1, and open panel 2.

The accordion is initialized as follows:

$( "#accordion" ).accordion({
    active: false,
    heightStyle: "Content",
    collapsible: true
});

When I click one of the IDs, the first click is always ignored (the correct accordion is not displayed). It only shows the correct accordion on the second and later clicks. The DOM is ready at the time I do the first click. I do not know what else to check. Any ideas?

Edit:

I have now added console.log for entering the function and clicking the element to the ViewClient() function, and what happens is that with every click, I do get the log message "entering", but the clicking only works on the second click onwards. What is strange though, is that it does not seem to "reset" the event:

entering

entering
clicking 204
clicking 206

entering
clicking 204
clicking 206
clicking 206

entering
clicking 204
clicking 206
clicking 206
clicking 206

Note that the second time I clicked, I clicked on a different ID (206). But it does the same thing if I clicked the original ID as well (204). I tried returning false and preventDefault(). It seems to me like a delayed DOM update?


Solution

  • You've assigned two click handlers to the same element(s). The one in your script and the one in the markup both fire on every click. You need to initialize your accordions separately, and you should call ViewClient() in the jQuery click handler.