Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a modal from being drawn more than once?

This is a bit more abstract than the usual questions which I know goes against the spirit of things, but I'm hoping that I can still get a good response.

Here's the issue. We have a fairly complex web application that is written in PHP. The purpose is relatively unimportant, but simply put: We are using Comet / AJAX / JSON / JavaScript / PHP / MySQL (NO jQuery, however, native JavaScript only) to render controls that display data in real time. Throughout this application we are rendering popup modals using native JavaScript. It's fairly complex logic that tests for the existence of a modal with the same name on the page and prevents creating new versions of the same, and of course once created a layer is created to prevent interacting with links beneath.

The issue is that we have at least one modal that can be called multiple times before it is rendered on the page due to the time it takes the AJAX call to collect data from the database and assemble it for presentation. If a user were to 'double click' on said link they would be presented with two modals, one on top of the other. I've been able to actually render 8-10 of these. Interacting with the topmost modal appears to be broken because the user is actually effecting collapsible headers on the bottom-most modal. Once you start closing the dialog boxes and get to the bottom you can see where you've clicked.

So, my issue is this: What is the best way to prevent this behavior?

I've considered simply adding a function to the onClick event that would remove the onClick attribute from the link after the first click with a minor timeout (say 500ms). I've also considered trying to implement bit testing logic that would count clicks and only actually first the event after the first click and reset when the modal is closed.

What I'm wondering is if someone has any thoughts or suggestions or even has tackled a similar issue and has some insight on best practices to accomplish my goal in this instance.

Thank you very much.

like image 897
ephbaum Avatar asked Oct 04 '22 05:10

ephbaum


1 Answers

You can unregister the click handler once it fired:

var element = ...,
myClickHandler = function(event) {
    // ...
    element.removeEventListener('click', myClickHandler, false);
    // ...
}

element.addEventListener('click', myClickHandler, false);
like image 76
Ja͢ck Avatar answered Oct 13 '22 09:10

Ja͢ck