简体   繁体   中英

click then unclick jquery button not working

I'm trying to make a button which on one click it changes it's color, and on another click it returns to it's original form. something like clicked and unclicked.

I added a JSfiddle for you to look at it. https://jsfiddle.net/dw5y5xLx/3/

$('.genM').click(function() {

$('.genM').removeClass('selected');


$(this).addClass('selected');

});

thanks!

also, is there a way doing that by only using CSS HTML?

Thanks.

$('.genM').click(function() {
    $(this).toggleClass('selected');
});

I have updated the js fiddle for you, please check ( https://jsfiddle.net/dw5y5xLx/15/ )!

jQuery hasClass function can be helpful

$('.genM').click(function() {

    if($(this).hasClass('selected')){
            $(this).removeClass('selected');
    }else{
        $(this).addClass('selected');
    }

});

IDEA:

Is there a way doing that by only using CSS HTML?

Yes, there is a way how u could achieve that just by pure CSS and HTML. But, if you dont want to use js, you must have an HTML element that is able to keep the "pressed" or "unpressed" state all by itself, without js.

However, there is no such an HTML element, so you have to use something simmilar: Checkbox

<input type="checkbox"> have "checked" and "unchecked" state and it is practicaly the same as "pressed" or "unpressed".


SOLUTION:

The trick is to stylize the ckeckbox with CSS so it visually appears as a pressed or unpressed button. Here is an example how checkbox can be stylised - you need to modify the CSS in order to appear it like a button, not a toggle switch!

You will want to use CSS selectors like this (as shown in example):

input[type="checkbox"]:checked { ... },
input[type="checkbox"]:checked + .slider { ... },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM