How to disable non-input elements with jQuery (or js)?

Viewed 635

I am trying to disable a bunch of elements (divs that have onClick and other custom events) while a request is taking place.

I have tried with:

$("selector").children().prop("disabled", true);

Also with:

$("selector").children().attr("disabled", true);

Also with:

$("selector").children().attr("disabled", "disabled");

Neither of these worked, meaning that, they all kept their functionality even after disabled was applied to them.

To confirm that I am actually able to target all of the desired elements I tested with:

$("selector").children().css({backgroundColor: "black"});

All elements became black, so the targeting is correct.

I am open to any other suggestions on how to disable elements, basicly these are divs that should not be clickable (there are other events of interest, not just the click), for the duration of a request, once a div is clicked, that is why I am trying to temporarily disable them, and re-enable them again, once I receive the response.

1 Answers

The disabled property only applies to input elements, such as <input> and <button> for example. It does not apply to some <div> or <li> styled to look like a button or input (could be a div content editable).

To disable an element that is not a "real" input element, you can use $("selector").children().css({pointerEvents: "none"}); which will just prevent ALL events on that element and childs, no matter the event handlers binded.

To restore: $("selector").children().css({pointerEvents: "initial"});

pointer-events documentation




Edit to adress comments about keyboard events:

$("selector").children().prop("tabIndex",-1); will avoid a tab navigation to access an <input> or <button>.

tabindex documentation

But since your elements are <div>... I don't really think that is relevant. But try it and see if that add-on code really is necessary and feel free to comment for future readers. ;)

Related