Search code examples
jquerycssdynamicpseudo-class

How to change the hover pseudo class of an element using jquery


I have a few elements on a div that can be moved around by the user. In order to make their draggability obvious, I've been using the hover pseudo class.

So I have

.textbox
{ /*some style*/
}

and then I have a hover pseudo class for the draggable corners of the textbox:

.textbox:hover .ui-resizable-sw {background: rgba(0, 0, 0, 0.5)  !important;}
.textbox:hover .ui-resizable-se {background: rgba(0, 0, 0, 0.5)  !important;}
.textbox:hover .ui-resizable-nw {background: rgba(0, 0, 0, 0.5)  !important;}
.textbox:hover .ui-resizable-ne {background: rgba(0, 0, 0, 0.5)  !important;}

However, what I need to do now is to only let the CSS become applicable after a user clicks on a certain activate button (switchOn). If I leave the above lines in the CSS stylesheet then the styles will always apply, but I want them only to apply sometimes, and not at other times.

I've checked this and know how to do it: Can I do this with the :hover pseudo class?

The problem is I don't want to have to do it using jquery like this because jQuery can be slow and there might be quite a few elements on the user's div, I don't want things to get sluggish. Instead of changing the style dynamically via jquery, is there any way to attach or detach the css style to the object?

Something like this:

function switchOn()
{
     $('.textbox').addStyle('.textbox:hover .ui-resizable-ne, 'background: rgba(0, 0, 0, 0.5)  !important;');

}

Solution

  • One of the solution can be applying another class on click on the button then change the css defs.

    $('#my-button').click(function(){
        $('.textbox').toggleClass('active'); // .addClass('active');
    })
    

    then

    .textbox.active:hover .ui-resizable-sw {background: rgba(0, 0, 0, 0.5)  !important;}
    .textbox.active:hover .ui-resizable-se {background: rgba(0, 0, 0, 0.5)  !important;}
    .textbox.active:hover .ui-resizable-nw {background: rgba(0, 0, 0, 0.5)  !important;}
    .textbox.active:hover .ui-resizable-ne {background: rgba(0, 0, 0, 0.5)  !important;}