What is the best way to create a button that functions as a toggle and changes its styling when clicked?

I have implemented the following code to update prices in my pricing table:

function updatePrices() {
  var x = document.getElementById("prijs-small");
  if (x.innerHTML === "17,50") {
    x.innerHTML = "13,50";
  } else {
    x.innerHTML = "17,50";
  }

  var x = document.getElementById("prijs-medium");
  if (x.innerHTML === "58") {
    x.innerHTML = "30,50";
  } else {
    x.innerHTML = "58";
  }

  var x = document.getElementById("prijs-large");
  if (x.innerHTML === "128,50") {
    x.innerHTML = "61";
  } else {
    x.innerHTML = "128,50";
  }
}
.price-button {
  background-color: white;
  color: #012d5d;
  padding: 10px 20px;
  border-radius: 30px;
}
<button class="price-button" onclick="updatePrices()">150/350</button>

<div id="prijs-small">17,50</div>
<div id="prijs-medium">58</div>
<div id="prijs-large">128,50</div>

Now, I am looking to create a toggle switch that mimics this functionality, displaying 150 (people icon) on one side and 350 (people icon) on the other side, similar to this example:

https://i.sstatic.net/U8MTF.png

Currently, the price change is triggered by a button. How can I convert this into a toggle switch with the green half representing the active part?

Thank you for your help!

Answer №1

Do you think this will work? I created a checkbox that resembles a pill using some CSS styling. It should be pretty straightforward, but feel free to leave a comment if you need more explanation.

body {
  background-color: gray;
}

#mybutton {
  width: 8rem;
  height: 3rem;
  border-radius: 100rem;
  overflow: hidden;
}

#mybutton input {
  display: none;
}

#mybutton>label {
  display: flex;
}

.side {
  width: 50%;
  padding-inline: 0.15rem;
  text-align: center;
  line-height: 3rem;
  background-color: white;
  transition: background-color, color 300ms;
  cursor: pointer;
}

#mybutton input:not(:checked)~.left {
  background-color: #35CB8C;
  color: white;
  transition: background-color, color 300ms;
}

#mybutton input:checked~.right {
  background-color: #35CB8C;
  color: white;
  transition: background-color, color 300ms;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div id='mybutton'>
  <label for='mybutton-checkbox'>
  <input type=checkbox id='mybutton-checkbox'>
  <div class='side left'>25<i class="fa fa-user" aria-hidden="true"></i></div>
  <div class='side right'>100<i class="fa fa-user" aria-hidden="true"></i></div>
  </label>
</div>

Answer №2

To display two buttons side by side, you can use border radius to give them a unique look.

Here is a basic example:

div.toggle {
  font-size: 0; /* to eliminate space between the buttons. Alternatively, you can use flexbox */
}

button {
  width: 100px;
  height: 50px;
  font-size: 14px;
}

button.left {
  border-right-width: 0;
  border-radius: 20px 0 0 20px;
}

button.right {
  border-radius: 0 20px 20px 0;
}
<div class="toggle">
  <button class="left">25</button>
  <button class="right">100</button>
</div>

You can also add images or icons inside the buttons for further customization.

Answer №3

By incorporating two unique buttons with varying images, you can achieve the desired outcome. Utilizing CSS properties like

border-bottom-left: (desired px value)px and border-top-left: (desired px value)px
, you can customize the look of your buttons.

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

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

JavaScript Update Function for Pointers in Parse.com - Modify a Row with a Pointer

I am currently working with Parse and JavaScript. While I know the ObjectId from the Status_id-class, I am facing a challenge in updating the column in the Question_status-class due to it being of Pointer-type. Can anyone guide me on how to update a Poin ...

Is there a way to access the name of a generic type T class in TypeScript?

I'm currently working on incorporating the Service Locator pattern into my TypeScript project. Below is the snippet of my code: //due to only partial knowledge of TypeScript private static serviceMap: Map<string, any>; public static get& ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

Is it possible to inject code into HTML using JQuery?

Despite having looked at numerous examples and being aware of the answer to my question, I can't help but feel like I might be missing something. I suspect that the reason this isn't working is because I am running this code locally, rather than ...

Changing HTML lists into JSON format

I am facing a slight issue with my HTML template while trying to convert it to JSON. My goal is to convert a list of HTML messages into JSON format. I appreciate your assistance in advance. HTML Template <div class="message"> <div class="mes ...

Guide to Helping Users Customize JavaScript and CSS Files before Exporting as Embed Code

I have a vision to create a unique platform where users have the ability to log in to a customized dashboard, tailor their preferences, and then generate an embeddable code for age verification pop-ups on their websites. To kickstart this project, I'v ...

The Nivo Slider is stealthily concealing my CSS Menu

Although this question has been previously asked, I am still unable to make it work with the solutions provided; The website in question is I have tried changing the z-index on all menu items to 99999, but they are still appearing below. <div id="sli ...

Show a preview of an image in an HTML document

How can I display an image after uploading it? I attempted to use the following code, but it didn't work: onFileSuccess: function(file, response) { var json = new Hash(JSON.decode(response, true) || {}); if (json.get('status& ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

If padding is included, the width of an element will be affected when using rem

I am facing an issue in my project. Whenever I try to insert a custom font-size at the html level, the red badges get deformed when there is padding (p-6) on the first line of code. Can someone assist me with this problem? I am using Tailwind CSS, but even ...

What steps can be taken to fix the issue of 'this is not defined' when trying to extend EventEmitter?

The code snippet below is encountering an error: var EventEmitter = require('events'); class Foo extends EventEmitter{ constructor(){ this.name = 'foo'; } print(){ this.name = 'hello'; co ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Updating form fields within nested forms using the FormBuilder array

The recommended method to change nested values according to the API documentation is using patchValue. For example, myForm.patchValue({'key': {'subKey': 'newValue'}}); But what if we need to change values in a nested array, ...

Sending Angular base64 image data to the server

I am encountering an issue while attempting to upload a base64 image from Angular to ExpressJS. The image is being created using html2canvas to generate the base64 representation. When I try to upload the imageData in its current format, I receive an error ...

Having trouble with Google Analytics tracking file downloads? Possible placement issues?

Uncertainty looms over me as I question the correctness of my placement... Seeking guidance on this particular aspect... An intricately designed web application that dynamically generates a roster of accessible resources, flawlessly processes file info va ...

There seems to be an issue with Angular 8's *ngIf not correctly updating the UI in the navigation bar

I am currently working on integrating bootstrap@4 with an Angular 8 application to ensure full responsiveness. In the navigation bar, certain elements such as the logout button or link should be hidden if the user is not registered or logged in, and vice ...

How can you position an element at the bottom of a div using CSS?

Could you please assist me in aligning an element to the bottom of a div using CSS? Below is a screenshot of my webpage for reference: http://prntscr.com/5ivlm8 (I have indicated with an arrow where I want the element to be) Here is the code snippet of m ...