Is it possible to create a button that can bring in a .css file?

Is there a way to create a button that imports styles from a .css file, or is it possible to change multiple CSS properties with buttons to create different website themes?

This is the CSS file I have:

.body {
    background-image: url("example.png");
}

And here's the HTML file:

<html>
<head>

<script>
    // ???
</script>

</head>

<body>
    <button onclick="???">Import!</button>
</body>
</html>

EDIT: I am open to using anything like jQuery as well. Any solution will do!

Answer №1

I have experience doing this multiple times. If you are interested, check out this tutorial for guidance.

You can utilize JavaScript to specifically target the href attribute and switch to a different stylesheet.

<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script>
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>


<button onclick="swapStyleSheet('new.css')">New Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>

Answer №2

Here is the solution you are looking for:

Check out the example below and click the button

$(".btn-success").click(function()
{
$('head').append('<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="jumbotron">
    <h1>My First Bootstrap Page</h1>
    <p>Resize this responsive page to see the effect!</p> 
  </div>
 <button type="button" class="btn btn-success">Click Me</button>
  <div class="row">
    <div class="col-sm-4">
      <h3>Column 1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 3</h3>        
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
  </div>
</div>

Answer №3

Give this a shot:

$('#colorize').click(function (){
   $('link[href="design.css"]').attr('href','theme.css');
});
$('#reset').click(function (){
   $('link[href="theme.css"]').attr('href','design.css');
});

Answer №4

Customizing the styles on your website based on button clicks is a simple task. You just need to detect when the button is clicked and then apply the appropriate stylesheet. You can even have different styles for different buttons, like a theme changer feature. Here's the code snippet to achieve this:

$('button.summer').click(function() {
    $('head').append('<link rel="stylesheet" href="assets/css/summer.css">');
});
$('button.winter').click(function() {
    $('head').append('<link rel="stylesheet" href="assets/css/winter.css">');
});

When the button with the class "summer" is clicked, the summer.css stylesheet will be added to the head section of your page. Similarly, clicking the winter button will add the winter.css stylesheet.

This method involves creating separate stylesheets for specific themes, while keeping common styles in a main stylesheet like general.css or style.css. This way, the custom styles don't replace the overall theme stylesheet but complement it by adding unique styling elements as needed.

By following this approach, you can easily customize and enhance the appearance of your website based on user interactions. Hopefully, this explanation helps you implement these changes effectively.

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

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Incorporating JSON objects into MySQL through a For Each loop - Checkbox Selections

My attempt to update the table (auth_users) with checkbox values using QueryBuilder and the provided code is not functioning correctly for the checkboxes on my form. I suspect that the issue lies in $key, "'".$value."'" not matching the DB field ...

Performing condition checks within the foreach loop and displaying numerous results in a single row

I have a list of results from searching certain parameters and I need to print them out. When using a foreach loop to print the results, I want to ensure that if the purchase dates are the same, they should be printed in the same row. How can I achieve thi ...

Using a variable with the :contains selector

function checkAndUpdateStatus(newName) { $('#myTable').children('tr').remove(":contains('" + newName + "')"); }; The function above is attempting to remove table rows in 'myTable' containing a string matching the ...

Completely different method for transmitting an array to NodeJS through AJAX

Recently, I've encountered difficulties when sending arrays to NodeJS using AJAX. It seems that whenever I try to send it with JSON, the error function is always triggered. Despite seeking explanations, I haven't found a satisfactory answer. The ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

Nodemailer fails to send out emails despite the absence of any error messages

I'm currently working on setting up a confirmation email feature for user sign-ups on my website. I've tackled similar tasks in the past, but this time I've hit a roadblock - the emails are not being sent, and there are no error messages to ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

I am experiencing a CSS display issue on the mobile version of my map leaflet where only the header and footer are visible

I am experiencing a display issue on Android and iPhone due to conflicting css commands. Here's what's happening: I am using React + React Leaflet with a header, main, and footer all set to width 100% within a parent div with body set to width an ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Generating a fresh array by filtering out elements with specific properties using the .map() method

Within my React application, there exists an array containing key value pairs where each pair corresponds to a checkbox. Upon checking the checkbox, the value of the corresponding key switches between true and false. The structure of the data retrieved is ...

Is there a method to initiate the Jquery Dialog without needing to use the .dialog registration function?

I am currently facing an issue with my page that contains multiple tabs. These tabs are loaded dynamically and one of them is a message container for mail. Every time I click on a folder link (such as Inbox or Sent Mail), only that specific tab gets reload ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...