Pimpy
Pimpy

Reputation: 51

Dont call hover events on disabled elements

is there some way to call hover events on disabled html elements? I found solution with wrapping div, but it doesnt work very well.

Forexample:

<input type="text" id="someidtext" value="somevalue" disabled="disabled" />
<select id="someidselect" disabled="disabled" > 

$("#someidtext").mouseenter(function () {});
$("#someidselect").mouseenter(function () {});

Thanks

Upvotes: 1

Views: 88

Answers (3)

Jai
Jai

Reputation: 74738

See ids should be unique so if you have class names then you can do this:

$(".someidtext:not(:disabled)").mouseenter(function (e) {
     console.log(e.type);
});

or more global:

$(":input:not(:disabled)").mouseenter(function (e) {
     console.log(e.type);
});    

Demo with :input


:input is the selector which selects all input elements whether that element is select, text, submit, button, textarea etc.

Upvotes: 0

Alex
Alex

Reputation: 10226

There are two possible solutions at least. First, add a condition inside the handler function like so:

$("#someidtext").mouseenter(function () {
    if (!$(this).attr('disabled')) {
        // the function code
    }
});

Secondly, you can bind event using delegation to inputs which are not disabled in the first place:

$(document).on("mouseenter", "#someidtext:not(:disabled)", function () {
    // the function code
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

I think the best solution is to check the condition within the handler.

$('#someidtext').mouseenter(function (event) {
    if(!this.disabled){
        console.log('x')
    }
})

Demo: Fiddle

If that is not possible, you may have to think about event delegation based handlers like

<div id="someidtext_wrapper">
    <input type="text" id="someidtext" value="somevalue" disabled="disabled" />
</div>

then

$('#someidtext_wrapper').on('mouseenter', 'input:not(:disabled)', function () {
    console.log('x')
});

Demo: Fiddle

Note: These solutions are based on the assumption that the disables state changes dynamically after the event handlers are registered

Upvotes: 4

Related Questions