Can I change the classname in a script when I change page - javascript

Hallo All,I have a problem. I have written a very extensive script to change my body-background from a page-specific background-image to an other background-image. For refrence:My 'mypage.html' has a default background of class='image1' defined in the default stylesheet.I have written a script to change this to class='image10' or class='image11', which are defined in the persistent stylesheet. (Believe me, this is the short version, but this part works... well, is going to. No questions here.)My 'otherpage.html' has a default background of class='image2' defined in the default stylesheet and I want to be able to change this as well to the same 'image10' and 'image11' from the persistent stylesheet.Both default backgrounds have multiple differently colored versions in alternate stylesheets... Change the stylesheet and class='image1' links to another version of the image.All this is directed by cookies that are page specific as well. This makes finding a solution quite important, because otherwise I would have to set cookies for every single page. Which I find unacceptable.My question is, do I have to copy/past the whole script to my 'otherpage.html' and change al the 'image1's to 'Image2's or is there a way to javascript something like:
if(HTML = 'otherpage.html') {
(".image1" = ".image2")
}
Excuse my very amateuristic script. I have looked all over, but I wouldn't even know how to search for this... Hope someone can help, otherwise copy/past it is ;)

You can use this little script here
var currentPage = window.location.pathname;
if (currentPage == "/somepage.html") {
// change the body class name
document.getElementsByTagName("body")[0].className = "image2";
}
You can use a switch statement if you have multiple pages to test.

You can control the styles(background and other styles) through the base class which you can set it to body tag of the document or any root container. On page load check the page name and set the class names accordingly.
if(page == "otherPage"){
document.body.className = "image2";
}
Now all the classes falling under image2 will be applied.

Related

Auto Swap External CSS Stylesheet with toggle scripting

Hi I am trying to get this script to toggle back to original CSS external stylesheet.
I have the following code that works.
$(document).ready(function() {
$("#css-master2").click(function() {
$("link[title=change]").attr({href : "css/master2.css"});
});
});
Whenever someone clicks on anything with id #css-master2 it changes the external style sheet to master2.css (that part works fine).
What I would like it do is change back to the original master1.css if they click on it again. Something like toggle?
Any help would be greatly appreciated.
Check for the link tag's href, if it equals master2, switch back to master1 like the same way above.
Can't think about why you'd do this, considering the exact thing can be done using css classes instead of two different files.

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

create css class on the fly in codebehind

I have a search page that is used in multiple places with multiple 'themes' throughout my site. I have a few divs that can have their background color changed based on a radio button selection (whether they are enabled or not). I can do this just fine by changing the css class of the div on the fly with javascript.
However, these themes could potentially change, and the background color is grabbed from a database when the page is created. Right now I do this in the C# codebehind:
string bgStyle = "background-color:" +theme.searchTextHeaderColor +";";
OwnerSearchHeader.Attributes.Add("style", bgStyle);
In the Javascript I need to change this color to make it look disabled, and when the user clicks back to this div I need to re-enable it by changing it back to its original color. But since I only knew this color in the code-behind, I don't know what it was in the Javascript.
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Alternatively I could create a hidden element, assign it the 'enabled' style, and use that as a reference in the JavaScript when enabling my div. This seems like a hack but maybe its the easiest way. I'm still new to a lot of this, so I'd appreciate any suggestions. Thanks for the input!
So my thought was to create a css class in the resulting HTML page when the page is loaded with the background color I need. Then I could simply switch from the divEnabled and divDisabled class in the javascript. But I'm not exactly sure how to do that.
Yes, this is the anser; do this. In the <head> of your document add a <style> and put your CSS in there like so: (my Asp.NET is a little rusty so forgive me if it has some hicups ;) )
<style>
<!--
.divEnabled {
background-color:<%=theme.searchTextHeaderColor%>;
}
.divDisabled {
background-color:gray; /* or wtv */
}
-->
</style>
You could also put it in an external CSS file, which may be a good idea.
Then write some JavaScript to add/remove the class attribute (I'm going to ask that you don't call is the "CSS Class" ;) )
var ownersearchheader = document.getElementById("<%=OwnerSearchHeader.ClientId%>");
// changing the class attribute to `divDisabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivEnabled\b/, "divDisabled")
ownersearchheader.setAttribute("class", newClassAttribute);
// ... or,
// changing the class attribute to `divEnabled`
var newClassAttribute = ownersearchheader.getAttribute("class").replace(/\bdivDisabled\b/, "divEnabled")
ownersearchheader.setAttribute("class", newClassAttribute);
This is indeed a mouthfull, so, like #Haydar says, you might want to use jQuery, which offers easy-as-pie addClass(), removeClass() and toggleClass() methods.
You can use the jquery .toggleClass method.
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
Here is the link to the api doc.
Jquery API

How to change the CSS of entire page/website on click?

Is it possible to have 3-4 CSS on a page, and then on any event, say click, change the css for entire webpage. This way we can give our user the ability to change the theme. I know we can change the css of an element by:
$("#myElementID").removeClass("class1").addClass("class2");
Yes, it is possible. Typically what you would do is write a JavaScript function that will change, or add, or remove a style sheet from the <head> of the document. To make the experience a little better you'll typically store the user's preference in a cookie. There's an article on A List Apart that show how to implement this.
And of course, you can do this with jQuery... you may want to check out the source of jStyler.
The CSS Zen Garden (see the fifth question) ended up deciding that the easiest way was just to refresh the page and set a new CSS server side.
CSS is emdeded to DOM over 'link' tag, so you can locate this link and add/remove
Following code shows how to remove and add new one (I'm using MS AJAX see method $get, but you can replace it with pure DOM or other dialect):
var head = document.getElementsByTagName('head')[0];
var oldLink = $get("nameOfLink", head);
if(oldLink!=null)
head.removeChild(oldLink); //remove old entry
var s = document.createElement('link');
s.id="nameOfLink";
s.type = 'text/css';
s.rel="stylesheet";
s.charset ='utf-8';
s.href = "http://your-provided-url";
head.appendChild(s);
Usually best to load an external stylesheet (append a <link>): http://snipplr.com/view/3873/failsafe-load-for-attaching-stylesheet/
But if you need to create a bunch of styles on the fly, you can also build and append a <style> node to the DOM: http://jonraasch.com/blog/javascript-style-node

How can I use javascript to convert relative href attributes into absolute paths?

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.
Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...
Right now all of the links are linking to relative paths back to the root.
For example
Home
News
Media
Other
I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?
$("a").each(function() {
alert(this.href);
$(this).attr("href") = this.href;
});
In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:
$('a.external').each(function() {
$(this).attr('href', domain_name + $(this).attr('href'));
})
you don't need jquery for such a simple function....
var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
var relativeLink = eachLink.href;
var absoluetLink = ["http://",domainName,"relativeLink"];
eachLink.href = absoluteLink.join("");
}
something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P
It's very simple:
$('a').each(function(){$(this).attr('href',this.href);});
When you read the href property of a HTMLAnchorElement, you get the absolute path, so you can overwrite it with attr() method of JQuery.
I noticed that all the solutions here only work with href attributes that begin with a "/" character. If you want something more robust, you may want to try the js-uri library. It looks cool but I haven't tried it myself so I don't know how buggy it is.

Categories