How to change stylesheet with Jquery and Django - javascript

Hello I've been trying to solve this problem for quite a while. Back when I was using vanilla html this code seems to work. (Changing from tile view to list view). Now that I have incorporated it in django and the hrefs contains static tags, I dont know how to refer to it in jquery and change its href. Pls help
HTML
<link rel="stylesheet" type="text/css" href="{% static "Stylesheets/tileVersion.css" %}">
I want to change it to this css href
<link rel="stylesheet" href="../Stylesheets/listVersion.css">
JQUERY
$('#listicon').click(function () {
$('link[href="static/Stylesheets/tileVersion.css"]').attr('href', 'static/Stylesheets/listVersion.css');
});
$('#tilesicon').click(function () {
$('link[href="static/Stylesheets/listVersion.css"]').attr('href', 'static/Stylesheets/tileVersion.css');
});
I want to be able to switch between them if possible. Any kind of help would be appreciated

You can do one of two things.
You can use static references to load one CSS file over another, by using a if tag in your code getting the css link value (the address/url) from a variable or from a data source. This compiles during server time. This also means that only one css is loaded at runtime. This is static for the client. For example:
Same as #1, but you can use an inline if to determine which one goes forward to the client.
Lastly, ensure both css files are held within the static process, and maintain your jquery:
$('#listicon').click(function () {
$('link[href="{% static /path/to/first/css/page %}"]').attr('href', '{% static /path/to/first/css/page %}');
});
$('#tilesicon').click(function () {
$('link[href="{% static /path/to/second/css/page %}"]').attr('href', {% static /path/to/second/css/page %});
});
I typed this out of memory, so please bear with me.
Hope this helps.

Just put an additional attribute id for the link tag. You can remove the current stylesheet from head and add another one.
<link rel="stylesheet" id="myid" href="../Stylesheets/listVersion.css">
$('#myid').remove();
$('head').append( $( '<link/>', {'rel' : 'stylesheet', 'id': 'myid', 'href':'newlink' } ));

Related

CSS file is not being loaded dynamically via ng-href

I am trying to dynamically load different css styles into my page using ng-href, but the page is not being updated with the activated style. Code is as follows:
<html ng-app="myapp" ng-controller="myController as myctrl">
<head>
<link rel="stylesheet" ng-href="../assets/css/{{ myctrl.style }}.css">
</head>
</html>
In my controller, I do the following:
vm.style = "redStyle";
pub.subscribe('style', function(theStyle) {
vm.style = theStyle;
});
The variable in the subscribe is updated with the new style once a publish has taken place. But the respective css file is not being loaded such that the style is updated on the page. Any ideas what I am missing out on?
Here is a working demo
It's very much the same as what you have so it's something else in your code. Hard to tell unless you put up all your code.
Assuming the stylesheet actually does exist, and the style variable is getting updated then my guess is that the culprit is
pub.subscribe()
If this callback is being triggered by something outside of angular then angular wont see the updated variable. You can bring it back into angular space like so:
pub.subscribe('style', function (theStyle) {
$scope.$apply(function(){
vm.style= theStyle;
});
});
Try this:
<link rel="stylesheet" data-ng-if="myctrl.style" data-ng-href="../assets/css/{{ myctrl.style }}.css" />
I solved it differently.
In my html, I gave the link element an id:
<link id="theme" rel="stylesheet" ng-href="../assets/css/{{theme}}.css">
And in the controller I say:
var myTheme = document.getElementById("theme");
var path = "../assets/css/{{theme}}.css";
myTheme.href = path.replace("{theme}", theme.class);

How to remove reference of specific CSS files files from View

I have many JavaScript Files and CSS Files referenced in the Layout file. Now I have a couple of views which are referencing some custom libraries which are interfering with the existing CSS files. So my question is can I somehow remove those references from these two views only or not allow them to load at all in the said views.
What you can do is, create a custom css file which overrides the existing styles from your regular (ex : bootstrap) css file. You can include this css files conditionally after your regular css styles in the views you want.
You may also use the !important attribute to explicitly override the values as needed.
So in your layout, add a new Section called CustomStyles
<head>
<!-- Existing css include goes heree -->
#RenderSection("CustomStyles", required: false)
</head>
And in your specific view, you can simply include the custom css file
#section CustomStyles
{
<link href="~/MyCustomCss.css" rel="stylesheet">
}
EDIT : As per the comment.
If you are ok to completely ignore the specific css files in some views, you can update your Layout to conditionally include/exclude those.
So in your layout
<head>
#if (ViewBag.IncludeBootStrap == null|| (bool) ViewBag.IncludeBootStrap !=false)
{
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
}
</head>
And in the view's in which you do not want to load this css file, Set the ViewBag.IncludeBootStrap value to false.
#{
ViewBag.IncludeBootStrap = false;
}
<h1>This view will not use bootstrap styles</h1>
Give an id to the tag.
<link rel="stylesheet" href="style1.css" id="style1" />
<link rel="stylesheet" href="style2.css" id="style2" />
And use this code:
You can use whatever event you want or just use the code without an event it's your choice
$("#A").click(function(){
$("#style1").attr("disabled", "disabled");
});
Note: While there is no disabled attribute in the HTML standard, there is a disabled attribute on the HTMLLinkElement DOM object.
The use of disabled as an HTML attribute is non-standard and only used by some Microsoft browsers. Do not use it. To achieve a similar effect, use one of the following techniques:
If the disabled attribute has been added directly to the element on the page, do not include the <link> element instead;
Set the disabled property of the DOM object via scripting.

Change entire CSS file on refresh

All other questions I've found relating to this are about changing specific elements, or changing the CSS file with a button, but what I'm looking to find out is:
Is there a script that will swap an entire CSS file whenever the page is refreshed?
I.e. I've got my core style.css and supplementary {color}.css files which replace certain elements in style.css, and I'd like those supplementary CSS files to be loaded randomly on refresh.
Sorry, I don't even know where, to begin with this. Hopefully, someone can offer some pointers?
Thank you.
Fundamentally this is just a matter of picking something at random, e.g.:
<head>
<!-- ... -->
<script>
var sheets = ["sheet1.css", "sheet2.css", "sheet3.css"];
var sheet = sheets[Math.floor(Math.random() * sheets.length)];
document.write('<link rel="stylesheet" href="' + sheet + '">');
</script>
<noscript>
<link rel="stylesheet" href="sheet1.css">
</noscript>
<!-- ... -->
(One of the rare cases where document.write isn't actually a bad solution.) Note the noscript fallback will always use the same stylesheet on browsers with JavaScript disabled.
All you need to do to load a CSS-file with Javascript is to add a <link> element to the DOM/body and it will be loaded automatically.
So in your <head> section you could include a <script> tag that just randomly selects a color.css from an array and generate the link tag, preferably as early as possible in the file to prevent flickering.
<script>
var colors = ['red.css', 'blue.css', 'green.css'];
var colors_idx = Math.floor(Math.random()*colors.length);
document.write('<link href="'+colors[ colors_idx ]+'" rel="stylesheet" type="text/css" />');
</script>
(PS. There are cleaner ways to inject HTML, keeping it concise to focus on the solution. Use your favorite approach, document.write can be a bit fickle.)

Find a script in head with jquery based on it's data-attribute

In my content editor you can change custom webfonts on the fly. If you change a font, it deletes all scripts and styles using the data-attribute as an identifier and the new ones then get appended after an ajax call. Now after some testing i realised it work's very well with css files but it ignores the < script >'s. Any ideas? Here is my Script:
$('head').find('[data-fontset-id=ce-fontset]').each(function() {
$(this).remove();
});
For example this is how the head section looks like:
<link data-fonset-id="ce-fontset" rel="stylesheet" href="..........">
<script data-fonset-id="ce-fontset" type="text/javascript" src="//use.typekit.net/xxxxx.js"></script>
<script data-fonset-id="ce-fontset" type="text/javascript">try{Typekit.load();}catch(e){}</script>
In this example, the css file gets removed but the javascript files didnt, any ideas why they are being ignored?
Thanks a lot in advance,
Michael

ASP.NET MVC Inserting CSS file in header via JavaScript depending on screen size

Im working on a MVC3 application, with a masterpage which renders the views in the body.
Now I have 2 css files (different layouts), and I want to select the CSS depending on the screen size of the client.
Everything works with the code below, however, only for the index page, whenever I go to a second page, whatever it is, no CSS is rendered at all.
The code below is placed in the HEAD section of the masterpage.
<script type="text/javascript">
var css = './Content/SiteWide.css'
if ($(window).width() < 1140) {
css = './Content/SiteNarrow.css';
}
var tempcss = '<link href="TEMPCSS" rel="stylesheet" type="text/css" />';
var cssLink = tempcss.replace("TEMPCSS", css);
document.write(cssLink);
</script>
So somehow the css doesnt load again when you go to a second page (all using the same masterpage), do you guys have any ideas?
thanks
Use CSS media queries instead of Javascript.
<!-- dropped rel attribute -->
<link media="only screen and (max-width:1139px)" href="SiteNarrow.css" />
<link media="only screen and (min-width:1140px)" href="SiteWide.css" />
Ideally you create one CSS file for one state, and have another override that when conditions are met.
<!-- dropped rel attribute -->
<link href="base.css" />
<link media="only screen and (min-width:1140px)" href="override.css" />
I believe you need to use Url.Content(). I.e.
#Url.Content("~/Content/SiteWide.css");
The pathing may be incorrect when you navigate from your Index page if you use
./Content/SiteWide.css
I've usually found Url.Content() to be the right thing to do when pathing to files in the project
Pro-tip: Don't use static file locations. Make use of Url.Content.
Your code would look like:
var css = '#Url.Content("~/Content/SiteWide.css")';
Try this out and see if it works. From experience I've had static locations sometimes not work as expect, whereas Url.Content did the trick for me.
I recommend implementing Responsive Web Design
http://www.sitepoint.com/responsive-web-design/#fbid=UhFHwQrRwnn
You can use what are called "Media Queries" to dynamically apply different css files or properties as the screen size changes, in real time. Very cool!

Categories