How to make the effects of jQuery's $(element).css() persistent? - javascript

For example, with a font-size switcher/button, if I use
$('#container p').css('font-size', '24px');
it works as expected, but if I later add paragraph elements to the container (via ajax, etc), they are not styled with the updated font-size. I am aware that this is the intended behavior of the .css() method. I am simply asking:
What's the proper approach to changing a style for a CSS selector, and making those styles persistent?

Right, well, when you perform that command, it styles all p elements in #container. If you want it to be permanent, you could create a <style /> element and add the CSS stylings there.
To elaborate, you could do something like this:
$(document.head).append('<style>#container p{font-size: 24px;}</style>');

What jQuery does in that line is equivalent to:
<div id='container'>
<p style='font-size:24px'>a</p>
<p style='font-size:24px'>b</p>
<p style='font-size:24px'>c</p>
</div>
For your particular case I'd get one of the stylesheets present in the document, like this:
var stylesheets = document.styleSheets
Which returns an array of styleSheet objects that contain the insertRule method, which you can use to add your new (permanent) css rule.
Cheers!

You cannot add the style directly w/ JavaScript, but you can however do this:
<div id="wrapper">
<div id="paragraph1">blah</div>
<div id="paragraph2">you</div>
</div>
and
$("#wrapper").css...
This way any paragraph you add to the wrapper will have the new font size...

Well you are adding style to exiting elements only, there is no way for jquery to know about the new elements.

The problem is probably that you are destroying the element upon which you have the style.
If you are bringing in via AJAX a replacement for #container, then all of the content will get destroyed and replaced with the new content. All of the <p> tags you added the style to will no longer exist, and it will need to be repeated on the newer entry.
What you could try is creating a class definition on the fly.

Related

Accessing a div with a complex class name

In the code below, I've marked a <div> with "LINE BELOW". I need to set css background attribute but, no matter how I try the syntax in jQuery or JavaScript, it seems like it never recognizes the thing! Why won't it accept my CSS definition?
As a bonus explain to me how to override the existing background attribute that contains !important in it.
This is the approximate scheme of what I have in a target website:
<div id="main-content">
<div id="detailblock">
<div class="tabsblock">
<section class="editblock">
<form id="target">
<div class="editblock-item">
<div class="input textarea">
<div class="editor_box">
//LINE BELOW:
<div class="editor_ editor_text">
//Something inside of div...
</div>
</div>
</div>
</div>
</form>
</section>
</div>
</div>
</div>
I tried this and found during research and it didn't work:
jQuery(".editor_.editor_text").css("background","#000 none repeat scroll 0% 0%");
What am I doing wrong?
UPDATE
I just tested and colored all divs in blue using css(). They all worked, except that particular one. But if I remove all divs using remove(), it will get removed with all divs. But if I remove that particular div using it's selector, it will not get removed!
you're not really selecting a <div> with a complex class name; you're trying to select a <div> with two class names assigned to it. Your jQuery selector does not have to contain both of those class names; either will do, though of course you can specify both if you want. Does $("div.editor_") select the element you want to change? Does $("div.editor_text")?
Once you have figured out the proper selector, you can either call jQuery's .css method on the selected element:
$(...).css("background", "blue");
or you can edit the selected element's style property directly (as in, not through jQuery). If you are attempting to override a CSS !important directive, I believe this is the method you must use:
$(...)[0].style.setProperty("background", "blue", "important");
(this works because two CSS rules are now marked as equally !important, and the order of application dictates that the one you're setting will win out.)
You have a typo here there is an extra space between the two editor:
<div class="editor_ editor_text">
Works fine without the extra space in this fiddle:http://jsfiddle.net/yutzjbjr/
edit
I see now that there are two classes involved. You should include your jquery in the question.
However still works fine with two classes: http://jsfiddle.net/yutzjbjr/1/
Can you maybe read the console?

Removing effect of a CSS selector

My requirement is a bit tricky. I have a mark-up as below: (just an example, real mark-up is very complicated)
<div class="classA">
<div class="classB">
<p class="classC">
<span class="classD">
</span>
</p>
</div>
</div>
As you can see above, there are four CSS classes classA, classB, classC, classD associated with the markup.
Also I have used jQuery to bind events using these selectors.
My Requirement: I want the jQuery event binding to work and at the same time, the CSS should not get applied i.e. I want to negate the impact of CSS styles from a UI perspective, but from functional perspective jQuery event handlers should still work.
So, is it possible to override the CSS selectors such that their styles don't get applied to my mark-up elements ?
example below:
div.classA div.classB p.classC span.classD{
color:red;
}
I don't want the font color to be red, so I tried to override the selector as follows, but its not working:
div.classA div.classB p.classC span.classD{
color:red;
}
div.classA div.classB p.classC span.classD{
/*no styles here*/
}
Please help !!
Then just delete those classes from css. jQuery will still work though.
There is no requirement that only classes used in css have to be used in jquery.
For example:
<div class="someUnknownClass"></div>
Even though, there is no someUnknownClass defined in css, $('.someUnknownClass') will still work.
Use another class name for the selector. So you have classA for the css and classX for the selector.
If you don't want the styles applied. Then you could use $('selctor').css(); to over write the styles. Bit hacky!
OR.
Add a class that over-rides the css. Or remove the class that holds the css.
using: $('selctor').addClass('no_styles'); OR $('selctor').removeClass('current_styles');
I don't know any mechanism allowing to do that the way you want it.
the work around i would suggest would be binding your events on anoter css class and doing something like this :
$('.classD').addClass('eventClassD').removeClass('classD');
$('.eventClassD').on('myEvent', function(){...});
like this you will still have events binded to your elements and would get rid of all the css.
You want to do it without modifying the JS? There's no clean way to do that. But try this.
Presumably you will have something that distinguishes this special set of elements to distinguish it from other elements, of which styles' you want to retain. This is difference probably manifests itself in the form of a different parent container. Just copy the set of CSS rules that affect these classes, and prepend this parent CSS selector with the pre-class values.
"Basically, I do not want to touch the js code, and only if something can be done on the css front, then my requirement is achieved."
If that is all you need, then just remove all of the css definitions from the page.
$("link,style").remove()

Separate ID and Class for JS and CSS

In several jquery tutorials, separate ID and Class are used for JS and CSS. for example
<div id="test" class="test">TEST</div>
As ID is used in the jQuery code, and Class is used in CSS. To me it is easier to not introduce Class and use ID for CSS rule too. Is there any advantage to use css-less ID for javascript?
EDIT: Thanks folks! I know the difference between ID and Class; I am asking why some use separate ID and Class for JS and CSS when one is sufficient. Here, the matter is the necessity for uniqueness of ID. The case is separating JS and CSS tasks (while they are closely entangled).
EDIT2: As requested, I give a typical example: this Tutorial. Look for actionsBox; .actionsBox has been used for CSS and #actionsBox for JS. As you can see there is only one <div> so ID would be enough for styling.
Read “Don't use class names to find HTML elements with JS” for some reasons why you may want to avoid using classnames in JavaScript.
This all boils down to personal preference, really.
Edit: #Sharon commented a link to a great article that discusses the drawbacks of using id selectors in CSS.
One reason people might only use classes in CSS is the specificity of the id selector.
If you’ve got two style declarations for one element, and they specify different values for a property, then the style declaration with the more specific selector wins out.
For example:
HTML
<div id="test" class="special-test"></div>
 CSS
#test {
color: red;
}
.special-test {
color: blue;
}
The ID selector trumps all other selectors for specificity (see http://www.w3.org/TR/selectors/#specificity for the rules), so here, the <div> will be red.
People who added class="test" to the <div> would presumably have written this:
HTML
<div id="test" class="test special-test"></div>
 CSS
.test {
color: red;
}
.special-test {
color: blue;
}
When both style declarations have selectors with the same specificity, the later declaration wins out, so here the <div> would be blue.
Personally, I’ve never found that to be a problem. In the first example, all you have to write to make the <div> blue is this:
#test.special-test {
color: blue;
}
But I guess some people find this aspect of specificity unnecessarily complex, and so avoid it by only using class selectors in their CSS.
(And I assume they keep the id because it’s faster to retrieve a DOM element in JavaScript by id than by class.)
You can use both ID and Class with both javascript and css. For example:
CSS
/*ID as identifier*/
#some_id {
<css attributes>
}
/*Class as identifier*/
.some_class {
<css attributes>
}
Javascript:
/*Get by ID*/
document.getElementById("some_id");
/*Get by class*/
document.getElementsByClassName("some_class");
The difference between the two is that ID will, or at least should be, unique and therefore will only affect or return a single element when applying css rules or selecting via javascript respectively. Class on the other hand is for affecting or selecting elements of a similar nature or classification.
If you had a car park with ten cars in it and you were to say "I want the car in space number three" you'd expect a single return whereas were you to say "I want the Fords from the car park" you'd expect to return every car in the car park which was a Ford. Css and javascipt use of ID and Class is no different.
EDIT: As per the OP's new redefined line of questioning.
css and IDs:
Css can harness IDs as an anchor so that the contents of a uniquely identified DOM object. Consider the folowing piece of css.
#some_id tr:nth-child(odd) {
background-color:#666888;
}
In the above example the css is tied to a unique identifier which in this case the ID is assigned to a table but the css rules themselves are applied to the odd rows within the table. In other words the css in this case affects table row elements where TR itself is an object class (not to be confused with css class).
In short, for ID at least, it is useful to use IDs within css and when you consider that jQuery and the likes of support Class-based queries using Class for selection within javascript is also useful.
Curious about the dual nature of "ID" in javascript and CSS. If you visit this example from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_blocks
you'll see the which is "naming" this particular <div> with the name "myDiv". This is because javascript getElementById("myDiv") is used later to modify the text contents of this specific <div>
BUT - if you add the line of code:
<style> #myDiv { color:blue; } </style>
you now have a CSS id with the same name as the javascript <div id>
The sample code in the w3schools does indeed change the color of the <div> called "myDiv" to blue. But when you push the "try it" button on that page, the CONTENTS of the javascript <div> also changes, which is the point of the w3schools example. Ie., it's teaching you that getElementById("myDiv") is how you can retrieve and modify contents of a named <div>
But because the identically named CSS #myDiv id is in force the <div> contents are changed, and they remain blue due to the style sheet.
So when you see a <div id="myDiv"> inside an HTML page, how can you readily tell if this <div> wants CSS id treatment? Or if this <div> will be referenced by some javascript getElementById() method?
Maybe you should check out the differenc between ID's and Classes:
http://css-tricks.com/the-difference-between-id-and-class/
I have never heard of using classes only in CSS and ID's only for JavaScript.
The main thing is ID's are unique, thats why they are called identifiers. If you have the same styling of a div over and over again on your webpage you should use a class to style them.
EDIT: It's not common or maybe its not allowed, I'm not sure, that ID's start with a number !
You can use id and / or class in JS and / or CSS. It all depends what you want to select. If you want to select a single DOM element, feel free to use id. If you want to select a group of related elements you might be better off using class.
Id should(read: must) be unique. A class is a set of object that have similarities, for example all lists on the page should look the same (but then you should use the list selector instead of a seperate class for it.
They have different purposes.

Dynamically add referenced stylesheet to inline styles

Scenario
I have created a page where the client can build their own page, calendars, widgets, articles etc. I have created a second Dynamic builder page where they can build their own newsletters.
Problem
All my css is referenced with classes, because mailers are very limited I have to add all styles inline.
Question
Is there a script I can run to grab all referenced styles via class, and add it to the relevant elements/tags inline-styles?
Example [simple]
<p class='txtBlack'>Hello World</p>
Converts to
<p class='txtBlack' style='color:#000;'>Hello World</p>
Hope this is clear enough to understand.
I'd use element.currentStyle and window.getComputedStyle() for each element, then 'manually' read what I want and overwrite what I'm sure that doesn't work in mail apps.
I made example here: http://jsfiddle.net/Vmc7L/
Another way, is to read rules form style sheets and then apply them to inline style. But what if u got selectors like .myClass:firstChild>.anotherClass? :D Maybe jquery can help.
There're methods you need: http://www.quirksmode.org/dom/w3c_css.html
This so answer explains how:
Can I access the value of invalid/custom CSS properties from JavaScript?
CSSStyleDeclaration (https://developer.mozilla.org/en/DOM/CSSStyleDeclaration)
div {
width: 100px;
}
style:CSSStyleDeclaration object contains cssText:
cssText: "width: 100px"
CSSStyleDeclaration specification: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
To get all elements with class names use:
jQuery("[class]")
Here is the solution u can use the "getElementsByClassName" javascript function to collect the elements with the class names specified. But remember this doesnot work IE browsers. So for IE u have to have your own function. Hope this helps u.

Get values from original css file using jQuery

I am running in to this situation. Basically my site has many templates of css and users can change the color dynamically using jQuery. Now, the way I did it was to use jQuery to modify the css property directly by selecting the classes. However, if users switch to a different template (also dynamically), I insert .css file in but it has NO effect what so ever. The reason is the css change style=".." for each elements take precedent. How to fix this issue? I am thinking of 2 ways:
Delete the style="..." at each elememts. But how to do this?
Get the values directly from within .css file and assign to each elements again as style="..."
Anyone can show me some light on either one? Thanks.
If you just want to remove the style attribute from a group of elements you can use:
$('p').removeAttr('style');
Just replace 'p' with all the elements you want to remove the inline CSS from, e.g:
$('input, div, h1').removeAttr('style');
Hope this helps.
Before you switch out the style from the original using jQuery, why don't you assign the original style value to data on that element, and then restore it using that value.
So, for instance, say you're changing the css font-family of an element with class "foo":
To apply new css:
var orig = $(".foo").css('font-family');
$(".foo").data('origFont', orig);
$(".foo").css('font-family', 'Arial');
To revert the css:
var orig = $(".foo").data('origFont');
$(".foo").css('font-family', orig);
Get rid of all inline CSS using this regex in your editor:
style="[^"]*"
i just had the same problem, but i think the best solution is to use the jquery add and remove class.
each template should have a class, then to change it, use the remove class and add the desired class

Categories