Implementing different CSS on page - javascript

I want to implement different CSS style sheet using javascript or code behind on aspx page so that for different web browser my page look better. Can anyone have some solution about this problem? I try a lot to implement that but failed.

Generally you don't want to go down the route of dynamically generating CSS with Javascript. The best approach to CSS is to:
Use a reset CSS;
Declare a DOCTYPE on every page; and
If necessary, include IE-specific additions (because, let's face it, it's always IE that causes the problems).

To add to Ravia:
You can use Request.Browser to get browser versions:
HttpBrowserCapabilities bc = Request.Browser;
if (bc.Browser == "IE" && bc.Version == "6.0")
{
HtmlLink link = new HtmlLink();
link.Href = ResolveClientUrl("~/CSSFile.css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(link);
}

I'd go with the server side option (aspx in your case).
check the 'user_agent' request header to determine the user's browser type
logically include a different css file based on this variable

HtmlLink styleSheet = new HtmlLink();
styleSheet.Attributes.Add("rel","stylesheet");
styleSheet.Attributes.Add("type","text/css");
styleSheet.Attributes.Add("href",ResolveClientUrl("MyStyleSheet.css"));
this.Page.Header.Controls.Add(styleSheet);
Check this out.
You can even set the style by adding a literal to your head tag and add the css style as text to this literal.
Happy coding.

Related

check if less file exists or not

I'm wondering if it is possible to check if a particular less file has called in the header section.
If it is there, I'd like to perform some js action.
Do you know any solution how could I check this?
Thank you in advance!
if ($('head link[href$="yourFileName"]').length) {
// ... (do your thing)
}
But as #LeoJavier suggests, you'd be looking for a .css file, not .less.
The browser doesn't read less files... it reads the css file generated by the less file.
You can use normal jQuery or javascript selectors to access the link element and then do your logic based on if the href is the path to the file you are referencing.
For example javascript to select the link element and href:
var linkElement = document.getElementsByTagName("link");
var linkHref = linkElement.getAttribute("href");
Note: I assume you mean CSS file rather than LESS file?

How to remove CSS and JS from a certain content-type in Drupal 7

I've come here after looking for how to selectively add a CSS or JS to a given node based on its view mode and content type. That question is answered pretty straightforward here (http://stackoverflow.com/questions/8295498/how-to-add-css-and-js-files-on-node-pages-independent-of-the-theme).
Now I'd love to clear everything: I'm looking for a way to show my desired CSS and JS but only that, with no other JS and CSS. I'm trying to integrate Impress.js (And I don't like the available solutions) and it seems to be conflicting with Jquery, as both scripts are properly loaded but both latest Firefox and Chromium browsers throw the "old browser" message.
Any ideas on how to unset every single CSS and JS so that the CSS and JS I want to use are the only ones really active?
Thanks!
I've tried the following, to no success:
$mycss = $vars['styles'];
unset($micss[drupal_get_path('module','system') .'/system.base.css']);
...
unset($micss[drupal_get_path('module','toolbar') .'/toolbar.css']);
$vars['styles'] = $mycss;
(I added a lot of different css i want to get rid of, but this explains the idea). It didn't work, though :)
Edit. I'm sorry for the bad markup, I'm looking for a way to clean/mark code.
In your custom module use:
function yourmodule_js_alter(&$js) {
unset(
$js['misc/drupal.js'],
$js['misc/jquery.js']
.... etc.
);
}
You say you want to only do this for certain content types, so try:
if(arg(0) == 'node') {
$node = node_load(arg(1));
if($node->type == 'your_content_type') {
unset(
$js['misc/drupal.js'],
$js['misc/jquery.js']
.... etc.
);
}
}
Jonny

How to determine whether a linked resource loads successfully

I'm using the following JavaScript to dynamically load stylesheets:
function set_stylesheet(name) {
var link = document.getElementById('userstylelink');
link.href = link.href.replace(/[^\/]+\.css$/, name + '.css');
}
Is there any way to determine whether the new CSS file is loaded successfully? If it fails, I'd like to be able to apply a default stylesheet.
You might want to see my answer to another similar question here:
Detect and log when external JavaScript or CSS resources fail to load
Basically, you can add an onload callback to see if the file was loaded. (If you load via JS of course)
The simplest way is to check styleSheet.cssText property of the link element after a new href was assigned.
function set_stylesheet(name) {
var link = document.getElementById('userstylelink');
link.href = link.href.replace(/[^\/]+\.css$/, name + '.css');
if ( link.styleSheet.cssText ) {
//if not empty string, it was loaded
}
else {
link.href = "default.css";
}
Alternatively there is "onerror" event which fires when the resource fails to load after href assigned.
Ideally, you would load them all at the beginning and then switch between then.
http://www.alistapart.com/articles/alternate/
http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
That doesn't really answer the question, but I think this way is preferred.
I'd recommend loading via ajax, checking the response as the user pimvbd mentions, but also place a dummy rule at the end of your stylesheet that styles a hidden element with a declaration you can check. For example, give a hidden div border: 987px and check to see if the hidden div's border is in fact 987px. Yes, it introduces a dependency on that style and that element. I've had endless discussions on this with many people, and there's not really a better way (yet). Hopefully s get some attention in browser releases in the near future...
There is a solution that requires no javascript or detection of whether the stylesheet loaded.
It seems you could also apply your default style with a built-in style sheet and then have the dynamically loaded stylesheet override the defaults. If the new stylesheet doesn't load, the default is already loaded and in place, nothing further to do. If the new stylesheet does load, it just overrides the default values and shows the new style.

Drupal - special css file if JS is turned off?

I'm building a Drupal theme up and want to know if there is a Drupalish way to add a css file only if the user has js turned off.
This would ideally go in the theme.info file to keep it neat!
Something like this would be ideal:
conditional-stylesheets[if no javascript][all][] = nojs.css
If this isn't possible then I'm going to keep all the css that needs JS out of the css files, and add it dynamically using JS but this seems a bit messy...
Any ideas?
You don't need conditional comments or noscript-tags for that. By default, Drupal adds a 'js' class to the html element and sets a cookie if javascript is enabled:
// Global Killswitch on the <html> element
if (Drupal.jsEnabled) {
// Global Killswitch on the <html> element
$(document.documentElement).addClass('js');
// 'js enabled' cookie
document.cookie = 'has_js=1; path=/';
// Attach all behaviors.
$(document).ready(function() {
Drupal.attachBehaviors(this);
});
}
(That's on line 296 in /misc/drupal.js.)
All css selectors that should only apply when js is enabled, can be prefixed with .js. If you want, you can put those css rules in a separate file, but you don't have to.
I don't know drupal that well, but it's a good question either way. According to W3Schools, the <noscript> tag is allowed only within the body element, so that is out.
Have you considered doing it the other way round? i.e. adding a script-specific CSS stylesheet using JavaScript? See starting points for that here.

In firefox, how can I change an existing CSS rule

In firefox, I have the following fragment in my .css file
tree (negative){ font-size: 120%; color: green;}
Using javascript, how do I change the rule, to set the color to red?
NOTE:
I do not want to change the element.
I want to change the rule.
Please do not answer with something like
...
element.style.color = 'red';
What you're looking for is the document.styleSheets property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE.
For example, try pasting the following in FF for this page and pressing enter:
javascript:alert(document.styleSheets[0].cssRules[1].cssText)
For me that yields the string "body { line-height: 1; }". There are methods/properties that allow you to manipulate the rules.
Here's a library that abstracts this interface for you (cross-browser): http://code.google.com/p/sheetup/
function changeCSSRule (stylesheetID, selectorName, replacementRules) {
var i, theStylesheet = document.getElementById(stylesheetID).sheet,
thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules;
for(i=0; i < thecss.length; i++){
if(thecss[i].selectorText == selectorName) {
thecss[i].style.cssText = replacementRules;
}
}
};
You can change CSS rules in style sheets through the CSS Object Model (currently known as DOM Level 2 Style). However, if you literally have "tree (negative)" in your style sheet that rule will be dropped and not appear in the Object Model at all.
As there is no HTML element tree I am going to assume that tree is the id or class of another element.
You would first retrieve the DOM element by id:
var tree = document.getElementById("tree");
Now tree represents your DOM element and you can manipulate it any way you like:
tree.style.color = "red";
Here is a great reference for mapping css properties to their javascript equivalent.
I'm not sure you can do actual class/selector overrides. You would need to target each element that used the .tree class and set the CSS. The quickest and easiest way would be through jQuery (or another similar framework):
$('.tree').each(function() { this.style.color = "red"; });
You could even use the built-in CSS functions:
$('.tree').css('color', 'red');
(I did it the first way to show you how standard JS would do it. The $(...) part is jQuery for selecting all elements with the .tree class. If you're not using jQuery, you'd need alternative code.)
If tree is an ID, not a class (there should only be one on the page) so using getElementById should be fine. Your code should look like the other answer.
for( var i in document.getElementsByTagName("tree") ){
document.getElementsByTagName("tree")[i].style.color = "red";
}
As I said in another answer's comment, I've never seen this done how you want. I've only ever targeted elements the same way as the CSS renderer would and changed each element style.
I did see this though: jQuery.Rule
It sounds like it does what you want but the demo causes my browser to flip out a bit. I'd invite you to look at the source to see it really does do what you want, and if you want to use it without jQ, use it as a starting point.
Edit: yes this should work. It works by appending another <style> tag to the page and writing out your overrides within. It's fairly simple to follow if you wanted to port it to plain JS.
For debugging, you can use Firebug to change the CSS rules on-the-fly.
If you want to change the rendered css rules from one page request to the next then some sort of server-side scripting will be required. Otherwise the original style sheet would simply reload at the next page request.
If you want to use an event on the first page to force the server-side action then you can use AJAX to actually change the CSS rule for the user.
"I want to change the rule so that
when I navigate to the next page, I
don't have to make all the changes
again."
It sounds like what you might want then is a remote request ("ajax") back to the server with the request you want to make, and generate a dynamic stylesheet which is sent back to the client?
How/why is this Firefox specific?
I want to change the rule so that when I navigate to the next page, I don't have to make all the changes again.
There are two approaches I can think of here. Namely client side and/or server side.
Client side:
Store the theme setting into cookies and load them up next time by javascript.
Server side:
If your site have an login system, you may also store the user preference into the database and generate the webpages with this inforamtion in mind next time on.
Utimately, you are still writing things like element.style.color =. But, they should get what you want.

Categories

Resources