Switch CSS file when button is clicked

I want to switch CSS pages by clicking a button in asp.net, but somehow I can’t do this. My code is as follows:

HTML:

<div> <h1>My Website</h1> <br/> <button>Night Mode</button> <button>Day Mode</button> </div> 

Script:

 <script> $(function () { $('button').click(function () { $('link').attr('href', 'Styles/night.css'); }); }); </script> 

Title:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <link href="Styles/day.css" rel="stylesheet" type="text/css" /> 

I have 2 css files in Styles folder like day.css and night.css. The page uses day.css and should switch to night.css when any button is pressed.

If I put the .html file and both .css files in a folder, it really works. But in Visual Studio (e.g. aspx page) this does not happen. I tried using other jQuery code like alert , it works fine. I can improve my code after that using a switch, etc.

+4
source share
3 answers

Got a response from Dave Ward. All I had to do was enable the preventDefault () method. Override the default behavior of the form.

+2
source

According to your requirement, this snippet will help you.

Follow these steps:

you need to create two css files in one place.

1: Day.css

2: Night.css

After that, use this code for css files to switch.

 <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="Day.css" id="styles" rel="stylesheet" type="text/css" /> </head> <script> $(document).ready(function(){ $('#mode').click(function(){ if($('link#styles').attr('href')=="Day.css"){ $('#mode').attr('value','Switch To Day Mode') $('link#styles').attr('href','Night.css') } else { $('#mode').attr('value','Switch To Night Mode') $('link#styles').attr('href','Day.css') } }) }); </script> <div class="table-responsive container"> <input type=button id="mode" text="Switch Mode" class="btn btn-primary" value="Switch To Night Mode" > </div> </html> 
+1
source

add id attr for the link and try to remove the link, then add a new link to this

 var newstyle = $("#style").clone().attr("link","newstyle.css"); $("#style").remove().after(newstyle); 
0
source

Source: https://habr.com/ru/post/1396833/


All Articles