Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a button with this code:

html:

<button style="background:url(images/bg.png);" onclick="main()"><font color="#FFFFFF">Image</button>
<button style="background-color:#000;" onclick="main()"><font color="#FFFFFF">Black</button>
<button style="background-color:#030;" onclick="main()"><font color="#FFFFFF">Green</button>
<button style="background-color:#006;" onclick="main()"><font color="#FFFFFF">Blue</button>

css:

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    font-size: 24px;
    background:url(images/bg.png);
}

Javascript:

<script type="text/javascript">
    function main(clicked){
        //Doesnt work
        document.styleSheets[0].cssRules[0].style.background="#00FF00";
    }
</script>

How can I achieve changing the background in the css file through the click of a button?

Answer №1

This example shows how you can achieve a similar result

<button>Press me</button>

const button = document.getElementsByTagName('button');
button[0].onclick = function() {
  document.body.style.background = "#FFFF00";
}

live demo link

Answer №2

It seems like your goal is to modify the background style directly within the CSS file.

Keep in mind that it's not possible to alter a CSS file hosted on a server through JavaScript alone. You'll have to trigger a server-side function to accomplish this task. Do you have any server technologies in place (such as PHP or ASP.Net)? If yes, you can set up a button click event to call a function on the server which will update the CSS file accordingly.

Answer №3

There are three ways to utilize CSS.

  1. Include a .css file and
  2. Use a <style> tag.
  3. Apply the style attribute within an element;

When we modify the appearance of an element with JavaScript, typically we alter properties within the style attribute. Although it is possible to adjust settings within the <style> tag, it is not recommended. Making changes in a .css file is also not feasible. Any alterations made within the <style> tag or using the style attributes only affect the DOM.

Therefore, it is impossible to modify External CSS with JavaScript. However, you can certainly change CSS properties within the style attribute. Execute the code below, open Chrome Inspector, select the <body> tag, click the button, and observe the results.

document.getElementById('changeBg').addEventListener('click', function() {
  document.body.style = "background:red;"
})
body {
  background: blue;
}

button{
  margin:100px;
}
<body>
  <button id="changeBg">Click here to change Background</button>
</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

Having trouble generating an array for checkboxes using jQuery, AJAX, and PHP

I'm almost there, but there's something missing. I'm attempting to send variables from multiple checkboxes to a PHP page using jQuery. This is my code: <div id="students"> <div class="field"> <label> ...

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

jquery interval randomly selecting a new option instead of verifying the correct answer

Below is a jQuery game created with aspx that runs on a 3000 millisecond interval. $(document).ready(function () { var interval; //initialize timer interval = setInterval(function () { //create timer ...

The displayed value in the text field remains constant even when the object's attribute is modified

My issue involves the Date Text Field component of Material UI. Whenever I pass an attribute from an object, the displayed value in the Text Field does not update even when the object attribute changes. const [data, setData] = useState({ title: new Da ...

Create a canvas and include input boxes in an HTML document

I'm attempting to create a canvas line diagonally above two textboxes that are also positioned diagonally (similar to Samsung's pattern passcode) when a button is clicked, but I am facing difficulties in achieving this. I have attempted to solve ...

OptinMonster's innovative feature - the Pardot form with an inline button

Having trouble integrating an HTML Pardot form into OptinMonster's floating footer option. I'm looking to align all three fields inline, along with the button. Can anyone assist me in placing the button inline with the fields? HTML: <fo ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Achieving the Menu Hover Effect - step by step guide to recreating this stylish effect

I recently came across a stunning hover effect on the main menu of a website (red rectangles above menu). It's quite impressive! I found it here: Now, I want to incorporate this same effect into my own website. Unfortunately, there doesn't seem ...

JQuery automatically selects an action upon 'change' event, but does not do so upon 'select' event

I'm hoping my explanation was clear. I have a text input field that utilizes the jQuery UI autoselect function. When a user selects an option, the input field auto-fills correctly. However, I encounter an issue when a user types something but does not ...

How can one extract information from an ASP.NET MVC on a separate webpage?

Experimenting with ASP.NET MVC for the first time here, so bear with me if this comes across as textbook-like. A basic content management system has been developed using ASP.NET MVC. The URL to retrieve a list of content, specifically announcements, looks ...

Is there a way to use jQuery to retrieve the date and time from a timestamp within an input field?

Hey, I've encountered an issue with jQuery and the UI date picker. Currently, my NEW event form has 3 fields: Date, timeFrom, timeTo. In my SQL database, I have corresponding fields: Date(datetime), timeFrom(time), timeTo(time). When a user selects ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

Trouble with sending input through Ajax in HTML form

I'm facing a dilemma that I can't solve. The issue arises from a page (index.php) that begins by opening a form, then includes another PHP page (indexsearch.php), and finally closes the form. The included page works with a script that displays d ...

What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definiti ...

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as <a href="/cdn-cgi/l/email-protection" class ...