scorpio1441
scorpio1441

Reputation: 3088

Change :active pseudo-class' style with jQuery

I'm developing some CSS editor and want to provide ability to change style for <button> when it's clicked. The following code doesn't change background-color to yellow.

http://jsfiddle.net/65erbrhh/

$('a').click(function() {
    event.preventDefault();
    $('button:active').css('background-color', 'yellow');
});

Edit: In my case, I can't assign specific class to a button, because it's user customizable html.

Upvotes: 2

Views: 5149

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240858

Since you can't select elements based on their CSS state, one option would be to add a class to the element:

Updated Example

$('a').click(function (e) {
    e.preventDefault();

    $('button').addClass('active-style');
});
button.active-style:active {
    background-color: yellow;
}

But since you said you can't do that, you could alternatively attach an event listener for the mousedown/mouseup events and change the background color accordingly:

Updated Example

$('a').click(function () {
    event.preventDefault();

    $('button').on('mousedown mouseup', function (e) {
        $(this).css('background-color', e.type === 'mousedown' ? 'yellow' : '');
    });
});

..but if you want the example to work if you mouseup outside of the button element, you would need to listen to all mouseup events:

Updated Example

$('a').click(function (e) {
    e.preventDefault();

    $('button').addClass('active-style');
});

$(document).on('mousedown mouseup', function (e) {
    var color = (e.type === 'mousedown' && $(e.target).hasClass('active-style')) ? 'yellow' : '';
    $('button.active-style').css('background-color', color);
});

Upvotes: 5

Related Questions