Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color change so far. Unfortunately, I'm struggling to figure out how to make the border color change as well.

function changeTheme() {
  if (document.getElementById("theme1").checked = true) {
    document.container.style.backgroundColor = "lightgray";
    document.container.style.borderColor = "red";
  }
}

function bgcolor(color, border) {
  document.body.style.background = color;
  document.body.style.borderColor = border;

}
<div class="dropdown">
  <input type="radio" id="theme1" name="theme" value="1" onclick="bgcolor('lightgray', 'red');" onchange="showFeedback('You changed the theme!')">Light<br><br>
</div>

The issue is that I have a square container in the middle of the page with a border, and when a theme is selected, the entire page's background color should change along with the border color of the central container. I attempted using onclick="changeTheme(), but it doesn't seem to be functioning properly.

Answer №1

In order to apply a border, you need to specify the thickness and style of it.

Avoid using inline styles or event handlers directly within the HTML code. Instead, assign a predefined class when an event occurs. Rather than checking if a radio button is selected, utilize the click event of the button. Once clicked, it's considered selected.

Moreover, if a form field is only serving as a user interface element and not intended for submitting data, omit the name attribute.

document.getElementById("theme1").addEventListener("click", function() {
  document.body.classList.add("lightTheme");  
});
.lightTheme { border:1px solid red; background-color:lightgrey; }
<div class="dropdown">
  <input type="radio" id="theme1" value="1">Light<br><br>
</div>

Answer №2

According to @Tyblitz's observation, the 'border' attribute must be properly configured:

function adjustStyle() {
  if (document.getElementById("style2").checked = true) {
    document.background.style.backgroundColor = "lightgray";
    document.background.style.borderColor = "red";
  }
}

function changeColor(color, border) {
  document.body.style.background = color;
  document.body.style.border = border;

}
<div class="dropdown">
  <input type="radio" id="theme1" 
   name="theme" value="1" 
   onclick="changeColor('lightgray', '6px solid red');"
   onchange="console.log('Theme altered!')">Light<br><br>
</div>

Answer №3

Update:
(Kudos to Scott Marcus for the insightful answer and Mike 'Pomax' Kamermans for the valuable comment)

Check out this pen.

I've implemented classes for different themes using a consistent naming convention: prefix "colorTheme" followed by the value of the input attribute.

function changeTheme() {
    /* Naming convention for theme class: prefix "colorTheme"
     followed by the input's value attribute */
    var themeClassValue = "colorTheme" + this.value;

    /* No action if clicking on the same input/label */
    if (themeClassValue != document.body.dataset.currentThemeClass) {

      document.body.classList.remove(document.body.dataset.currentThemeClass);
      document.body.classList.add(themeClassValue);
      /* Store new current theme value in custom data-current-theme-class attribute of body */
      document.body.dataset.currentThemeClass = themeClassValue;
    }
}

document.addEventListener('DOMContentLoaded', function () {
    /* Only needed at DOMContentLoaded, separate function created for this event */
    var selectedTheme = document.querySelector('input[id^="theme"]:checked');
    if (selectedTheme) {
        var themeClassValue = "colorTheme" + selectedTheme.value;
        document.body.classList.add(themeClassValue);
        document.body.dataset.currentThemeClass = themeClassValue;
    } else {
        /* If no input is checked, set data-current-theme-class to "null" */
        document.body.dataset.currentThemeClass = null;
    }
});

/* Select all inputs with id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');

for (let i = 0; i < themeInputs.length; i++) {
    themeInputs[i].addEventListener("click", changeTheme);
}


This method allows easy addition of new themes by following the established naming pattern.

function changeTheme() {
  /* Naming convention for theme class: prefix "colorTheme"
     followed by the input's value attribute */
  var themeClassValue = "colorTheme" + this.value;

  /* No action if clicking on the same input/label */
  if (themeClassValue != document.body.dataset.currentThemeClass) {

    document.body.classList.remove(document.body.dataset.currentThemeClass);
    document.body.classList.add(themeClassValue);
    /* Store new current theme value in custom data-current-theme-class attribute of body */
    document.body.dataset.currentThemeClass = themeClassValue;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  /* Execute code only when DOM content is loaded */
  var selectedTheme = document.querySelector('input[id^="theme"]:checked');
  if (selectedTheme) {
    var themeClassValue = "colorTheme" + selectedTheme.value;
    document.body.classList.add(themeClassValue);
    document.body.dataset.currentThemeClass = themeClassValue;
  } else {
    /* If no input is checked, set data-current-theme-class to "null" */
    document.body.dataset.currentThemeClass = null;
  }
});

/* Select all inputs with id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');

for (let i = 0; i < themeInputs.length; i++) {
  themeInputs[i].addEventListener("click", changeTheme);
}
html {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 16px;
}

*,
*::after,
*::before {
  -webkit-box-sizing: inherit;
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
  min-height: 100vh;
  width: 100vw;
  border: 10px solid;
  border-color: transparent;
  -webkit-transition: all .4s;
  transition: all .4s;
}

ul {
  list-style: none;
  margin: 0;
  padding: 10px;
  font-size: 20px;
}

li {
  padding: 2px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

input,
label {
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  outline: none;
}

.colorTheme1 {
  color: rgb(36, 36, 33);
  font-weight: 400;
  background-color: rgb(248, 236, 220);
  border-color: rgb(60, 75, 124);
}

.colorTheme2 {
  background-color: rgb(39, 34, 28);
  border-color: rgb(102, 102, 153);
  color: rgb(248, 236, 220);
  font-weight: 700;
}

.colorTheme3 {
  background-color: rgb(255, 0, 0);
  border-color: rgb(0, 255, 255);
  color: rgb(255, 255, 0);
  font-weight: 700;
}
<body>
  <ul>
    <li><input type="radio" id="theme1" name="theme" value="1" checked><label for="theme1">Light</label></li>
    <li>
      <input type="radio" id="theme2" name="theme" value="2"><label for="theme2">Dark</label></li>
    <li>
      <input type="radio" id="theme3" name="theme" value="3"><label for="theme3">Flashy</label></li>
  </ul>
</body>

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 best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

Developing a sophisticated responsive menu using Bootstrap 5 and Flex

I need a responsive menu that always maintains the appearance shown in the image below. Any overflowing content should trigger the addition of a scrollbar: https://i.sstatic.net/Gen7g.png Although my current solution works initially, it fails when additi ...

Show HTML content from different domains within a navigation tab's content area

I am in need of showing content from a different domain on my webpage within a navigation tab. I have followed the example given in the link below: Loading cross domain endpoint with jQuery AJAX This is how my HTML code looks like: <section class=" ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

When a JavaScript/jQuery open window popup triggers the onunload event after the about:blank page has been

Imagine you have a button that triggers a popup using window.open(): <button id = "my-button">Open window</button>​ You also want to detect when this popup window closes. To achieve this, you can use the following code: $('#my-button& ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Is there a way to differentiate between a browser application running on a local development server and an online staging server?

Is there a way to conditionally call a component only on the staging server and not on the local machine in Vue.js? <save-drafts-timer v-if="!environment === 'development'" /> ... data () { return { environment ...

Implement a custom placeholder feature for InputNumber in Blazor

I have a question about adding a placeholder to the InputNumber component. I attempted the following code but unfortunately, it did not work as expected. //Code behind public int? Hour { get; set; } //razor page <EditForm Model=&quo ...

When the dropdown form options in HTML are clicked, they appear disproportionately large compared to the initial select box

Sorry if my wording is a bit off, I'm still relatively new to working with CSS and HTML. I've encountered an issue where the dropdown options appear much larger than the select box itself when clicked. I can't seem to figure out how to fix i ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

When rendering inside *.map in React, the first object of the array may not be rendered

When the SearchCard component is being rendered, it seems to be skipping the first object in the array- const cardArrayTrackSearch = this.state.searchtrack.map((user, i) => { return ( <SearchCard key={i} reload={th ...

Check out the Pa11y JSON configuration file specifically designed for actions by visiting the following link: https://github.com/pa11y/pa11

Our automated accessibility testing is conducted using the Jenkins CI tool with the help of pa11y. Below is the Jenkinsfile used to execute these tests: node('mypod') { container('centos') { def NODEJS_HOME env.NODEJS_HOME = "${t ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

The login form is not being recognized by Chrome

I've been working on creating a login form for my website. Oddly enough, when I try to use it on Chrome, it doesn't prompt me to save my password. Yet, it functions properly on other browsers like Edge, Firefox, and Internet Explorer. Here' ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

Tips for generating automatic views in Backbone without manual instantiation

Is there a more efficient way to instantiate the view rather than directly below the definition? var BVApp = Backbone.View.extend({ Name: 'BVApp', // do chonka stuff }); $A.Class.add(new BVApp()); ...

Polygons that were deleted on Google Maps will reappear once you zoom out

I am working on a map project where I draw polygons. My goal is to remove the previously drawn polygon whenever a new one is being drawn. Initially, everything seems to work fine. However, when I use the scroll function on the map, the previously drawn po ...

Using Angular's $http service to send a file to a web API endpoint from a post function

I'm facing an issue with uploading a javascript file or transmitting a javascript file to a post function. On the client side, I am using angularjs $http service to send the data as follows: $http({ method: "POST", ...