A guide to using JavaScript to create a button that can dynamically change stylesheets

Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question.

With javascript, how can I code a button to switch stylesheets every time it's clicked?

I've experimented with different if, else if and else statements, but they always end up breaking the code (e.g., changing color to blue from red, but failing to revert back). It works fine with two buttons, but making it work with just one seems to be a challenge. In frustration, I added a second button to reset it back.

Here's the solution for 2 buttons:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>"Your Title Here"</title>
    <link id="um" rel="stylesheet" href="stylesheet1.css">
        <style>
        </style>

</head>

<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>

<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"} 
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"} 
}
</script>
</body>

Moving forward, looking to streamline it down to one button and function.

UPDATE... Attempted this approach, unfortunately didn't work out as planned.

    function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"}; 
else {document.getElementById("um").href = "stylesheet1.css"} 
}

Answer №1

Ensure that when comparing values, you use the == operator instead of just =!

if (document.querySelector(".nav").href == "style.css")

And so on...

Answer №2

Give this a shot:

<button id="x" onclick="updateStylesheet()">Change</button>

<script>

    function updateStylesheet() {
      var link = document.getElementById("um");
      var segments = link.href.split('/');
      var currentStyle = segments[segments.length - 1];
      var style =  (currentStyle == 'stylesheet1.css') ? 'stylesheet2' 
                                                       : 'stylesheet1';
      document.getElementById("um").href = style + ".css"
    }

</script>

Answer №3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>"Replace Title Here"</title>
    <link id="um" rel="stylesheet" href="styles1.css">

</head>

<body>
<p>foobar</p>
<button onclick="toggleStyles('um','styles1.css', 'styles2.css')">switch</button>

<script>
function toggleStyles(id, styleA, styleB) {
    var element = document.getElementById(id);
    var newHref;
    if(~element.href.indexOf(styleA)) {
        newHref = element.href.replace(styleA, styleB);
        element.href = newHref;
    } else {
        newHref = element.href.replace(styleB, styleA);
        element.href = newHref;
    }
}
</script>
</body>
</html>

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

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

When the "open" prop is set to "true", the DRAWER component from @material-ui/core fails to display

Help Needed: I'm struggling to make the drawer component open when the variant prop is set to "temporary". Material-UI Package Used: @material-ui/core I have integrated Material UI's drawer component into my custom Nav component. However, I am ...

The presence of an image within an HTML anchor is causing an unexpected artifact to

Currently, I am working on a simple header design, but there seems to be a strange issue with the anchors containing image tags. The problem can be seen in the screenshot below: Image Link Here is the HTML structure: <div class="block-content"> ...

AngularJS service failing to deliver promised result

I am in the process of retrieving data from my database using AngularJS. I have created a service to fetch the data and a controller to display it. Check out my code snippet: angular.module('myApp') .factory('panelService', [&apos ...

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

Using Javascript to extract formatted text from a webpage and save it to the clipboard

I've developed a straightforward tool for employees to customize their company email signature. The tool generates text with specific styling, including bold fonts and a touch of color - nothing too extravagant. When I manually copy and paste the styl ...

What is the best way to refresh the user interface while executing a lengthy operation in AJAX/Javascript?

With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept: var co ...

Create a composition of several debounce promises in JavaScript

I am looking for a way to efficiently manage multiple costly server calls by continuously invoking a function that accepts a key and returns a promise containing an object. This object is guaranteed to have the requested key along with additional values, i ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Securing API access by limiting it to verified domains with Express.js

I am currently enhancing the security of my Node.js/Express.js application by implementing restrictions on access to an authlist (authorized list) of domains. Note: The opposite of an authlist is a denylist. Overview: Users are able to create a Proje ...

Understanding the rationale for rendering Views with vuex dependencies in vueJS

I'm facing an issue with my API call in App.vue that populates the vuex store's state. The Home.vue component displays images based on the store's state, but console errors are thrown before the state is populated. I'm unsure about the ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

Error in Cordova Android Compilation ("unable to locate Build Tools version 24.0.1")

I'm currently experiencing some difficulties while trying to compile my Cordova project on Android. Upon entering the command "cordova build Android", I encountered the following error message: FAILURE: Build failed with an exception. * What caused ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...