Click and "Decrypt" on jquery button

Asked

Viewed 320 times

5

I have a Button created only in HTML and CSS, and I need that if someone click on it, a block <div> alter your background-color. With that maybe:

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

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

Using Jquery.

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

Do not call for HTML or CSS code, I believe you will not need, it is necessary to work only in js.

Just open in a new Guide : http://jsfiddle.net/c49fjwmz/.

2 answers

7

Your code includes a checkbox that stores whether the status of the button 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);
});

http://jsfiddle.net/c49fjwmz/3/

  • Thank you very much! It worked! I have one doubt left, if I want, for example that whenever the button is ON there is a variable "connected = true" and when it is OFF there is "connected = false", for other purposes, you could complement for me please ?

  • jquery toggleClass would also solve this issue well

2


Opa, I saw that the question has already been answered but wanted to contribute an alternative that focuses on the click of your input checkbox, and not on the div:

click: every time you click on the checkbox it executes 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: I saw that in the comment of another reply you requested the following: "whenever the button is ON there is a variable "connected = true" and when it is OFF there is "connected = false""

In this case you can use the following code:

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

He will return true if ON (checked) and false if it’s OFF. Whenever you need this information just run that code, without the need to instantiate a global variable.

I hope I contributed,

until.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.