Tips on using javascript to reset an element's inline CSS to its initial default styling?

I have a basic function that alters the default text styling when a checkbox is checked, and restores it to its original state when the checkbox is unchecked.

Despite my efforts, the terms.style = ""; line does not reset the style as expected. I am perplexed by this issue and cannot figure out why. I have confirmed that the else statement executes correctly when the checkbox is unchecked, as I manually tried changing the styles.

const form = document.getElementById('form');
const checkBox = form.querySelector('input[name=termsCheckBox]');

checkBox.addEventListener('click', function(){
    const terms = document.getElementById('termsText');
    if (checkBox.checked){
        terms.style = "color: black; font-weight: normal";
    } else {
        terms.style = "";
    }
});//end of function

Answer №1

To apply inline CSS to an element's `style` attribute, you can use the `getAttribute()` method to retrieve the current style, store it in a variable, and then add or remove it based on the checkbox state.

var checkBox = document.querySelector('#form input[name=termsCheckBox]'),
    terms = document.getElementById('termsText'),
    style = terms.getAttribute('style');

checkBox.addEventListener('click', function(){
  if (checkBox.checked)
    terms.style.cssText = "color:black; font-weight:normal";
  else
    terms.style.cssText = style;
});
<form id="form">
  <input type="checkbox" name="termsCheckBox">
  <textarea id="termsText" style="color:red; font-weight:bold">termsText</textarea>
</form>

Answer №2

As outlined on MDN:

It is advised not to set styles by directly assigning a string to the style property (such as elt.style = "color: blue;")

The proper way to do this is:

checkBox.addEventListener('click', function(){
    const terms = document.getElementById('termsText');

    if(checkBox.checked){
        terms.style.color = "black";
        terms.style.fontWeight = "normal";
    }else{
        terms.style.color = "";
        terms.style.fontWeight = "";
    }
});

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

HTMX allows for multiple events to be triggered on a single element, each event initiating a unique request

Looking to attach both a click and double click event to the same element in HTMX, with each event triggering a different request (or view). I'm new to using HTMX with Django and I have this list: <li class="list-group-item" hx-get=& ...

Using AJAX and jQuery, the result is retrieved and inserted into a <div> element

Having trouble populating a DIV with the result of a simple GET request using AJAX and jQuery. What could be causing the issue? <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <scrip ...

Unusual behavior observed while looping through an HTMLCollection returned by the getElementsByClassName method

After spending some time debugging, I discovered an issue with my function that changes the class of elements to modify their properties. Surprisingly, only specific elements were being affected by this change. It took me a while to troubleshoot and resolv ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

The JavaScript function I coded is capable of executing on its own without needing

The code snippet above defines a function called tablePush that is supposed to push an id to a table when an item is clicked. However, there seems to be an issue as the function executes without a click event. Below is the provided code block: function t ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...

Issues with Angular Component not detecting changes in @Input array

I'm dealing with a challenging setup where: The Parent Service (A) is imported in the Parent Component (B). Then, the Parent Component passes an array of Objects to a Child Component (C), which are referenced from the Parent Service (e.g. <child-c ...

Is it possible to alter the location of a button through a click event

On the left side of the container, there is a button with the text "Go Right!". When clicked in this position, the button moves to the right side of the container. When the button is on the right side, the text changes to "Go Left!" and clicking it will m ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

Comparing inline-block and block display options for displaying images

In this HTML snippet, there is a main div with the id of "main_div" that contains two sub-divs. The first sub-div has an id of "logo" and includes a link to a picture. The second sub-div has an id of "intro" and contains text. For reference, here is the o ...

What is the process for creating text within a rectangle using canvas, pixi.js, or three.js?

I've been tasked with creating a dynamic progress bar that shows the time remaining until a specific date. While I've successfully implemented the countdown feature, I'm now faced with the challenge of making the numbers fill in a specified ...

What is the method for configuring Google API's free Translate service to provide results in JSON format?

Looking to integrate a free Google translation API into my Chrome extension. You can access the API using this URL: The response from the API is in the format of an array, with a sample result like this: [[["नमस्ते","hello",,,1]],,"en"] Curr ...

The continuous firing of the postback event of the Asp.Net Button is

Why does the postback event keep firing for my button? Strangely, when I try to debug with Firebug and set a break point on the function(e) part, the code seems to skip right over it. Even using return false doesn't seem to resolve the issue. <sc ...

Searching across multiple attributes in Jquery UI Autocomplete: A comprehensive guide

My data is stored in an array of objects with a structure similar to this: $scope.usersList = [{ "name": "John", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb088898ade939f9d">[email protected ...

The image appears to be overlapping within the navigation bar

I'm having trouble understanding why the image is overlapping on this website. The image is enclosed in a link tag, and upon inspecting it, the link tag seems to be correctly positioned while the image appears slightly below. I can't seem to ide ...

I am encountering an issue with my authentication system where it is returning

I'm currently experiencing an issue with my authentication system using passport. For some reason, I keep getting an 'undefined' value returned. Can anyone provide assistance? Here is the code snippet in question: app.js passport.use(new L ...

Vue Functional Calendar - Easily manipulate selectedDates with the power of v-model

I am trying to set specific dates as selected in the vue functional-calendar (version 2.8.87) component (https://github.com/Digital-Threads/vue-functional-calendar). I have set up the v-model and can successfully detect dates selected by a mouse-click. Ho ...

Error: ChunkLoadError - Unable to load chunk for node_modules_next_dist_client_dev_noop_js

As I was working through the basics tutorial on the Next.js website, I encountered an issue when reaching the Global Styles step. The runtime error that started appearing is as follows: ChunkLoadError: Loading chunk node_modules_next_dist_client_dev_noop_j ...

Using localStorage in Next.js, Redux, and TypeScript may lead to errors as it is not defined

Currently, I am encountering an issue in my project where I am receiving a ReferenceError: localStorage is not defined. The technologies I am using for this project are Nextjs, Redux, and Typescript. https://i.stack.imgur.com/6l3vs.png I have declared ...

AngularJS- issue with button visibility on 'toolbar' widget

In my angularJS application, there is a page with multiple widgets displayed. When a user clicks on the 'Settings' button on the page (separate from the widgets), a toolbar for each widget appears showing different buttons depending on the widget ...