Modify CSS file from Javascript

1

Good morning everyone,

I'm designing a web in ASP where each user can select a "theme" for the interface (basically, the color of the header and others is red, green or blue). What I do is that each user, from his personal data page, select a color of the three and keep it in the database. Then I save that value in a session variable after the user logged in and, at the head of the Site.Master, I have the following

<link href="Content/StyleSheetGreen.css" rel="stylesheet" id="StyleSheet"/>
<script>document.getElementById('StyleSheet').href = "/Content/StyleSheet<%=dTema() %>.css";</script>

(dTema returns Red, Green or Blue)

The problem is that, when modifying the route from Javascript, it only loads the css in the home (www.loremipsum.com), but when entering in any other one (www.loremipsum.com/dolor) it does not find the CSS file

Any ideas?

Thanks in advance,

Andrés

    
asked by Andrés73 21.12.2016 в 14:35
source

1 answer

0

First, you are modifying the stylesheet by javascript, not by jQuery.

Second, you are using a relative path ( Content/StyleSheetGreen.css ) in loading the style sheet and then adding another with absolute path. Possibly the relative will be the one that generates these problems.

Assuming that the absolute path is more reliable (it will not generate problems in subdirectories), you should add this code to dynamically generate from the server the correct file from which to load the style sheet:

<!-- Estática, la normal -->
<link href="/Content/StyleSheetGreen.css" rel="stylesheet" />
<!-- Dinámica, la buena, generada en el servidor sin intervención de javascript -->
<link href="/Content/StyleSheet<%=dTema() %>.css" rel="stylesheet" />

It is unnecessary to inject through javascript something that you can do directly in the HTML from ASP.

    
answered by 21.12.2016 в 14:43