reggie
reggie

Reputation: 3674

Exclude elements from click event handler (jquery)

I have defined an event handler for some elements on the page.

var selector = "div, select, input, button";
$(selector).on('click', function (e) {
    //deactivate function of the elements and prevent propagation
    e.preventDefault();
    e.stopPropagation();
    //...
    //dialog is loaded and created here
    //e.g. $(body).append('<see-dialog-html-from-below>');
    //...
    alert('selector click');
}

I then add (and remove) a dialog to the DOM at runtime (one dialog at a time). A simplified dialog could look like this:

<div id="dialog" class="ui vertical menu">
    <div class="item">
        <label for="constraints">Constraints:</label>
        <select id="constraints" name="constraints">
            <option value="0">option 0</option>
            <option value="1">option 1</option>
            <option value="2">option 2</option>
            <option value="3">option 3</option>
        </select>
    </div>
    <div class="item clearfix">
            <div class="ui buttons">
              <div id="save_button" class="ui green button">Save</div>
              <div class="or"></div>
              <div id="cancel_button" class="closebutton ui button">Cancel</div>
            </div>
    </div>
</div>

I bind more click actions to the cancel and save buttons when I create the dialog.

The problem is the select box. It triggers the first click event that I defined above.

How can I exclude all elements in the dialog box from being included in the first event handler?

Upvotes: 2

Views: 4569

Answers (2)

m4ktub
m4ktub

Reputation: 3121

If clicking the select triggers the alert, in the first event handler, then the dialog already exists in the page by the time you execute $(selector).on('click', ...). In that case you can exclude some elements from the selector with not.

$(selector).not('#dialog').on('click', ...)

This will bind a click handler to all elements matched by the selector but excluding elements matched in the not. If you have several dialogs consider using a CSS class like ui-dialog and using not('.ui-dialog').

EDIT: But note that if your dialog is placed inside a div and you do not stop the propagation of the custom events then any click in the popup will bubble up and also trigger the handler in the parent div. Just ensure you use e.stopPropagation(); when adding handlers to the dialog actions.

Upvotes: 5

reggie
reggie

Reputation: 3674

I have solved this for now by adding a click event handler for all elements of the dialog like so:

$('#dialog > ' + selector).on('click', function (e) {
    e.stopPropagation(); //prevent the event from bubbling through the DOM hierarchy
});

If you know a solution how I could exclude the dialog at the time of creation of the handler, please let me know.

Upvotes: 0

Related Questions