Click and "Uncheck" button with jquery

5

I have a Button created just in HTML and CSS, and I need to have someone click it, a <div> block changes its background-color . With this maybe:

$(document).ready(function(){
    $('#button_on-off').click(function(){
        $(".bloco").css('background-color', 'rgba(255, 0, 0, 0.5)');
    });
});

But I want it to be transparent when the button is ON and when the button is OFF it will be colored.

Using JQuery.

Well, I already left everything commented and prepared in jsfiddle for you to help me.

Do not link to the HTML or CSS code, I believe you will not need it, you only need to work on js.

Just open in a new Guide: link .

    
asked by anonymous 03.07.2015 / 04:28

2 answers

2

Oops, I saw that the question was answered but I wanted to contribute an alternative that focuses on the click of your input checkbox, not the div:

click: every time you click on the checkbox it runs the code below:

$("#myonoffswitch").click(function() {
    var isChecked = $(this).is(":checked");
    var color = isChecked ? 'rgba(0, 0, 0, 0.5)' : 'red';
    $("#bloco").css('background-color', color);
});

Note that in the comment of another response you requested the following: "whenever the button is ON there is a variable" connection = true "and when OFF there is" connection = false ""

In this case you can use the following code:

$("#myonoffswitch").is(":checked");

It will return true if it is ON (checked) and false if it is OFF. Whenever you need this information, simply execute that code without the need to instantiate a global variable.

I hope I have contributed,

Until.

    
04.07.2015 / 17:17
7

Your code includes a checkbox that stores whether the button status is "on" or "off". You can use this state to determine the color. For example:

$('#button_on-off').click(function(){
    var cor = $('#myonoffswitch')[0].checked ? 'rgba(0, 0, 0, 0.5)' : 'rgba(0, 0, 255, 0.5)';
    $("#bloco").css('background-color', cor);
});

link

    
03.07.2015 / 04:36