Is there a way to remove the jQuery .css() upon clicking a different button?

I am currently working on a jQuery switch where I want the clicked button to revert back to its original state when another button is clicked. Additionally, I want the 'OFF' button to be automatically clicked first when the page loads. Despite trying various code snippets, I have been unable to achieve the desired functionality.

HTML:

<!DOCTYPE HTML>
<html>

<head>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src='script.js' type='text/javascript'></script>

</head>
<body>

<div class="switchcontainer">   
    <button id="darkmodeon">ON</button>
    <button id="darkmodeoff">OFF</button>
</div>

</body>
</html>

CSS:

body{
    background-color: black;
}

.switchcontainer{
    background-color: white;
    display: flex;
    justify-content: space-between;
    border-radius: 50px;
    width: 125px;
    padding: 5px;

}

button{
    width:50px;
    height: 50px;
    border: none;
    border-radius: 50px;
    background-color: #d8d8d8;
    color: #777777;
    font-family: 'calibri light';
    font-size: 17px;
    font-weight: bold;

}

jQuery:

$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });

        $(this).off('click',darkon);

    });

});

Answer №1

By utilizing classes and Jquery, achieving this task is quite simple.

Start by establishing a new class for the "on" state.

.on {
    background-color: #85c452;
    color: white;
    transition: all 0.2s ease;
}

Next, revise your click handlers to toggle this class on and off instead of directly applying specific CSS styles.

$(document).ready(function(){
    var switchOn = '#switchOn';
    var switchOff = '#switchOff';

    $(switchOn).click(function(){
        $(this).addClass("on");
        $(switchOff).removeClass("on");
    });

    $(switchOff).click(function(){
        $(this).addClass("on");
        $(switchOn).removeClass("on");
    });
});

Answer №2

By clicking a button, you have the ability to switch off the other button by adjusting the CSS properties of that particular button to inherit, which resets the properties to their default settings. You can target these buttons using $('#darkmodeoff') and $('#darkmodeon'), similar to how you utilize $(this).

To ensure that the OFF button is initially selected, you just need to apply the styles to it within $(document.ready). In this case, I've opted for

$('#darkmodeoff')[0].style.backgroundColor
and $('#darkmodeoff')[0].style.color.

Personally, it is recommended to include cursor: pointer to the buttons to give the appearance of being clickable, and outline: none to button:hover in order to eliminate the default blue border. These changes have been incorporated into the provided code snippet :)

$(document).ready(function() {
  var darkon = '#darkmodeon';
  var darkoff = '#darkmodeoff';
  
  // Set the off to clicked by default
  $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
  $('#darkmodeoff')[0].style.color = "white";

  $(darkon).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeoff').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

  $(darkoff).click(function() {
    $(this).css({
      "background-color": "#85c452",
      "color": "white",
      "transition": "all 0.2s ease"
    });
    $('#darkmodeon').css({
      "background-color": "inherit",
      "color": "inherit",
      "transition": "all 0.2s ease"
    });
  });

});
body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer; /* ADDED */
}

button:focus {
  outline: none; /* ADDED */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="switchcontainer">
  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>
</div>

Hopefully, this explanation proves to be beneficial! :)

Answer №3

Instead of using $(this).off('click',darkon);, try using $(darkon).trigger('click'); at the beginning of your darkoff event handler and $(darkoff).trigger('click'); at the beginning of your darkon event handler.

Don't forget to include }).trigger('click'); before closing the darkoff event handler.

Unfortunately, I'm unable to modify your code right now as I am currently using my phone.

Answer №4

  • If you wish to disable the event, you must provide the handler as an argument for the click event.
  • Instead of dynamically applying CSS, use a class to target the specific state for a cleaner approach.
  • To execute the handler upon page load, trigger the click event once the handler is attached.

var darkon = '#darkmodeon';
var darkoff = '#darkmodeoff';

// Proper way to bind the click handler to a button for future disabling of the event
$(darkon).click(addActiveClass);

$(darkoff).click(function(e) {
  addActiveClass(e);

  $(darkon).removeClass('on');

  $(darkon).off('click', addActiveClass);

});

function addActiveClass(e) {
   var $target = $(e.target);

   $target.addClass('on');
}

$(darkon).click();
body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
}

.on {
  background-color: #85c452;
  transition: all 0.2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switchcontainer">
  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the content remains centered within absolutely positioned DIVs inside the parent container

Imagine a scenario where you have a container with a fixed width and centered. Inside this container are two DIVs that are position relative to the window, placed side by side. The content inside these DIVs should ideally be centered, aligned with the cont ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

AngularJS component data binding is dysfunctional

I am currently experimenting with component binding in AngularJS for the first time. Unfortunately, I am facing some challenges as I am unable to get it to work correctly and pinpoint where the issue lies. In this scenario, I have two components: one is r ...

Is there a way to successfully press a button on a website?

While testing, I start by navigating in the constructor webBrowser1.ScriptErrorsSuppressed = true; webBrowser1.Navigate("http://www.tapuz.co.il/forums/forumpage/393"); webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted; Next, in the DocumentC ...

When clicking on HTML input fields, they do not receive focus

I am facing a puzzling issue where I am unable to access the input fields and textareas on my HTML form. The JS, HTML, and CSS files are too large for me to share here. Could someone provide guidance on what steps to take when troubleshooting this unusual ...

Interact with jQuery mobile radio buttons by triggering events on click

I have encountered an issue with jQuery mobile radio buttons where the onclick event is not fired on the first click, but rather on the second click. It seems like a double click is required for it to work properly. Does anybody know how I can fix this pr ...

Is there a possibility of Node.js being blocked during the processing of large file uploads?

Is it possible for Node.js to become blocked during the processing of large file uploads? Due to Node.js having only one thread, is there a risk that other requests will be blocked while handling large file uploads? If this is the case, what is the best ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

How can I preserve the line break in a textarea using PHP?

Is it possible to maintain line breaks in a textarea using PHP? Currently, I have a temporary solution that involves using the exec function to run a shell command, but I would prefer a purely PHP approach. Below is my temporary script - can you help me mo ...

Express server encountering difficulties locating requested file for download

I encountered a curious issue while working with my express server: I am attempting to download a file from a dynamically created folder. Below is the code snippet: var folder = id.toString() var file = [projectRoot,"/app/temp/",folder, "/regist ...

Tips for adjusting the width of Material UI TextField within a Table

I am utilizing a Material UI Table. This is how I construct it: tableValues.map((curRow, row) => { tableRows.push( <TableRow key={this.state.key + "_row_" + row}> {curRow.map((cellContent, col) => { let adHocProps ...

In search of the precise locator for conducting Selenium tests

During my project work, I've encountered the challenge of finding the correct locator for Selenium testing. Despite trying various combinations, I can't seem to locate the right one to click on a specific link. Every attempt results in a "No Such ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

Initiate the printing process by executing the window.print() function. As the document is being

Here's the code snippet : <body> <div class="headerCont noprint"> <div class="headerHold"> <div class="logoCont"><img src="images/logo.jpg" width="104" height="74" alt="Logo"> ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Execute a jQuery AJAX request to fetch and retrieve only the HTML content

Is there a way to perform an AJAX call that only returns HTML content without the browser retrieving additional resources such as images and CSS? I've noticed in the Network log that all the associated resources are being fetched as well. $.ajax({ ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Selecting a specific value in a row from an HTML table - a comprehensive guide

This is a similar structure where, if I check the first button, I can retrieve the January month savings stored in a text field. Hello everyone, I am looking to design a table that includes a checkbox in the first column of each row. Upon selecting this ...

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...