Ways to efficiently update styles dynamically using css and/or javascript

I am trying to update the styles of a button when it is clicked. I initially set the style for the first element on page load, but now I need to remove those styles from the first element and apply them to the clicked button instead. I am having trouble figuring out how to do this using nth-child(1). Can anyone provide guidance?

Below is my HTML:

<tr>
<!-- ko foreach: optionValues -->
<td>
    <input type="radio" id="volt" name="volt"
        data-bind="attr: {id: 'CC-prodDetails-' + $data.value}, value: $parent.selectedOption">
    <button data-bind="attr: {for: 'CC-prodDetails-' + $data.value}, text:key, 
                                                click:function(key){
                                                    $parent.selectedOption(key);
                                                    $parent.selectedOptionValue(key);
                                                }" class="voltagem"></button>
</td>
<!-- /ko -->

And this is my CSS:

input {
  display: none;
}

.voltagem {
  font-size: 20px;
  border-color: #333;
  border-radius: 10px;
  border-style: dotted;
  margin-left: 25px;
  height: 55px;
  width: 135px;
  background-color: transparent;
}

.voltagem:focus {
  border-color: blue;
  border-style: solid;
  outline: none;
}

td:nth-child(1) .voltagem {
  border-color: blue;
  border-style: solid;
  outline: none;
}

Answer №1

If you want to dynamically change the CSS class of an element based on a condition in Knockout.js, you can utilize the css binding. Simply set the class voltagem to the button when $parent.selectedOption() === key.

const model = function() {
  const self = this;
  const options = [ { key: "one" }, { key: "two" }, { key: "three" }];
  self.optionValues = ko.observable(options);
  self.selectedOption = ko.observable(options[0].key);
}

ko.applyBindings(new model)
.voltagem {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
  <tr>
    <!-- ko foreach: optionValues -->
    <td>
      <button data-bind="text: key, 
                         click: function(obj) { $parent.selectedOption(obj.key); },
                         css: { voltagem: $parent.selectedOption() == key }">
      </button>
    </td>
    <!-- /ko -->
  </tr>
</table>

Note: Remember to update the click binding function to include setting

$parent.selectedOptionValue(obj.key)
.

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

Does the frame take precedence over the button?

const div = document.createElement('div'); // creating a dynamic div element div.setAttribute('id', "layer1"); // setting an id for the div div.className = "top"; // applying a customized CSS class div.style.position = "absolute"; // sp ...

Using Jquery to add new HTML content and assign an ID to a variable

Here is some javascript code that I am having trouble with: var newAmount = parseInt(amount) var price = data[0]['Product']['pris']; var id = data[0]['Product']['id']; var dat ...

Canvas only draws outside the table, with the exception of the first one

I am facing an issue with placing multiple signature pads inside table cells. Only the first canvas gets drawn, while the others remain blank. I have checked the mouse/touch events. The events are triggered (up/down/move) and the draw function is called, ...

Calculating dimensions for parents and their children

Could someone please explain to me why the size of #child is different from that of #parent? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.or ...

Challenges encountered with the navigation bar in Bootstrap 4

I am facing an issue with positioning the logo on the left side of the top navigation bar. Every time I try to implement this, it ends up breaking the frontend design. Here is a snippet of the code: .top-line { border-bottom: 1px solid #cecece; } ...

Tips for containing a moving element within the boundaries of its container div

I have a dynamic box placed inside another box, and I want to restrict its movement within the boundaries of the parent container. How can I achieve this? In simpler terms: I need the frog to stay within the frogger. HTML <div id="frogger"> ...

Align the text to the right within a display flex container

Below is the code snippet: <div className="listContent"> <div> <div className="titleAndCounterBox"> <div className="headerListTitle">{list.name}</div><br /> <div ...

Access a three.js scene from a canvas element within the local environment to make alterations

Is it necessary to keep Three.js variables (scene, camera, renderer etc.) globally? I have devised a function that initializes canvas elements by taking a DOM position and other information to build the scene. This function is then passed to a render func ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Hover effect within nested CSS styling applied to the list item element

I have structured my HTML as follows: <div id="chromemenu" class="chromestyle"> <ul> <li><a rel="dropmenu1" href="#" class="">Buy</a></li> <li><a rel="dropmenu2" href="#" class="">Sell</a>< ...

The functionality of OnPress for React Native Google Places Autocomplete is hindered by its surrounding parent components

I'm currently implementing the react-native-google-places-autocomplete library in my React Native application. However, I've encountered an issue when trying to select an address from the suggested list provided by Google. Whenever I click on a s ...

The construction was unsuccessful due to errors in the webpack process

I encountered a sudden error in my Next.js app. Is there any solution available to resolve this issue? ./pages/_app.tsx Error: [BABEL] C:\Projects\skribeNew\app-web\pages\_app.tsx: You provided us with a visitor for the node type T ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

"Is it possible to differentiate between a variable that is BehaviorSubject and one that is not

I am dealing with a variable that can be of type Date or BehaviorSubject<Date | null>. My concern is figuring out how to determine whether the variable is a BehaviorSubject or not. Can you help me with this? ...

Top-align the background of the inline element

This particular inquiry pertains to a curious discrepancy in the computed height of an inline nonreplaced element across different web browsers. The question can be found here: Why the computed height of inline nonreplaced element differs between browsers? ...

adjustable backdrops

Hi there, I'm trying to create a background image that resizes with the window while maintaining its proportions. I want to achieve this using CSS only. I've been searching for a solution but haven't found anything that works for me. I even ...

I am having trouble printing because of document.write

Whenever I use javascript to create a document with document.write I include an iframe element then I try to print the contents using iframe.print() but nothing happens - no error message and no print dialog box. How can I successfully initiate a print ...

Top tip for combating form misuse in Django applications

Is there a reliable method to restrict form submissions in Django? I need the form to be submitted a maximum of 5 times from the same IP address within one hour. Can this restriction be implemented in Django? I experimented with Django Ratelimit, but unfo ...

Group By feature in AngularJS

Hey there, I'm trying to display a table from the code provided below. The issue I'm facing is with grouping by name. Here's how I want the view to appear: Shareholder | Preferred Stock | Common Stock | Options | Percentage | |----------- ...