What is the best way to remove this .click function?

My goal is to create a switch function where clicking the "on" button changes its CSS, and if the user then clicks on the "off" button, the CSS returns to normal. I also need the switch to default to the "on" position, but my attempts so far have been unsuccessful.

Here is the HTML code:

<!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="switch-container">
        <button id="darkmodeon">ON</button>
        <button id="darkmodeoff">OFF</button>

    </div>

</body>
</html>

This is the CSS code:

body{
    background-color: black;
}

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

}

#darkmodeon{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}

#darkmodeoff{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}

Lastly, here is the jQuery code:

$(document).ready(function(){

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

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

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#66e86a",
            "color": "white" ,
            "transition": "all 0.3s ease"   
        });
        $(this).unbind('click', darkon);
    });



});

Answer №1

.click(handler) is simply a replacement for .on('click', handler). To eliminate any previously attached handler for any event on any element, you can use:

$(selector).off('eventName', handler)

Here's an example:

var whatever = function(){
    // your code here
};
$(selector).on('click', whatever); // or $(selector).click(handler);
$(selector).off('click', whatever);

In the provided example showcasing how to unbind, the function is unbound immediately after being bound. In real scenarios, you would typically unbind based on your application's logic.

For instance, if you want to unbind a click event after the first click, you would usually use .off() inside the bound function:

var whatever = function(){
  $(this).off('click', whatever);
  // code that executes only on the first click.
};
$(selector).on('click', whatever); // or $(selector).click(handler);

In your specific case, have you considered toggling a class on the parent elements instead?

$('.parent button').on('click', function(){
  $(this).closest('.parent').toggleClass('on');
})
/*.parent button, 
.parent.on button:first-child {
  display: none;
}
.parent button:first-child,
.parent.on button:last-child {
  display: inline;
}*/

/* If you prefer not to use animations, you can just switch the simple `display` properties above */

.parent {
  position: relative;
  display: inline-block;
}
.parent button {
  transition: opacity .2s linear, transform .3s cubic-bezier(.4,0,.2,1);
}
.parent.on button:first-child {
  opacity: 0;
  transform: translateX(-100%);
}
.parent button:last-child {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  transform: translateX(100%);
}
.parent button:first-child,
.parent.on button:last-child {
  opacity: 1;
  transform: translateX(0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
  <button>On</button>
  <button>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

Refresh the Google Maps location using GPS coordinates

Currently, I am working with an Arduino that has a GPS chip and processing NMEA strings with Python. I have an HTML file set to auto-refresh every x seconds to update the marker's position. However, I would like to update the position information with ...

Is the scaling of a div with an image affected by odd pixel sizes?

My goal is to create a responsive grid with square images, where the first image is double the size of the others. While I can achieve this using jQuery, I am curious if there's a way to accomplish this purely with CSS. Grid: Here's an example o ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...

What is the best way to eliminate all borders from a select box?

Is there a way to completely remove all borders from the selectbox using either CSS or JQuery? The code snippet is as follows: <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option& ...

Using the <a> </a> tag for navigating within the code logic

Currently, I am utilizing the <a> tag for clicking and navigating, as shown in the code snippet below. I am looking to navigate this code using the C# tag in the page_prerender event, based on the selected id. Can anyone offer assistance with this? ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

When attempting to compile at runtime without an instance, the act of creating a function constructor can lead to an

My website is designed to function as a simple quiz game. It retrieves an array of JSON questions using AJAX, and for each question in the array, it displays the question itself along with buttons containing various options that were stored in the question ...

Is using .htaccess a reliable method for securing a specific file on the server?

Running a classifieds website comes with its own set of challenges, one being the need for an administrator to have the ability to remove classifieds at their discretion. To address this issue, I have developed a simple function that allows me to specify t ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Tips for storing mustache templates for rendering in Node.js

My data is stored in the following format: let data = {"list" :[ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9fafb8afef0f9f5e8f4fdb6fbf7f5">[email protected] ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

My collection consists of objects arranged in this manner

let attributeSet = [{ "id": 1, "value": 11 }, { "id" : 1, "value": 12 }, { "id" : 1, "value" : 13 }, { "id": "2", "value& ...

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

No entries found in the Nuxt/content module's array

<template> <div> <input v-model="searchQuery" type="search" autocomplete="off" placeholder="Search Articles" /> <ul v-if="articles.length"> ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...