Is it possible add or change CSS properties using jQuery? - javascript

Specifically, a class or id within the css.
Would you use something similar to $(window).height()?

It's not clear exactly what you want, but as a general rule all the styles applied to a given element can be accessed in JavaScript using something like:
element.style.<property-name>
So using native JavaScript you can do:
var elemStyles = document.getElementById("someId").style;
var styleWidth = elemStyles.width;
Assuming at least one element with a given CSS class and a framework that can select elements by class, you can similarly do:
var elemStyles = $(".someClass")[0].style;
var styleWidth = elemStyles.width;
Or depending upon what (if any) JavaScript framework you are using, there may be specialized methods that you can use to access/inspect various CSS attributes for a given element.
Note that any of these methods will bring back all the styles applied to the element, whether they are coming from the CSS file, from inline CSS declarations, or added programmatically by a script on the page. If you want to get just the styles inherited from the CSS file, then things get a bit trickier.

yes its possible
if you would like to receive other css properties check this out
http://api.jquery.com/css
you would do somethig like this
var cssvalue = $(selector).css(propertyName);

This will probably help you, too. Esp. if you want to do it without jQuery: How do you read CSS rule values with JavaScript?

Related

Use JavaScript to rewrite CSS with class and tag at the same time

I am able to easily change the style or the tag of an element based on certain criteria using JavaScript:
document.getElementsByTagName("mainclass")[0].style.color:#ffffff;
However, is there a way to do this is the style contains multiple classes and a tag like so
.mainclass .secondaryclass div td {
color: #000000;
}
The following is not working for me so im sure there is a totally different way of doing it:
document.getElementsByTagName(".mainclass .secondaryclass div td")[0].style.color:#ffffff;
...
The other option if easier is to figure out how to use JS to embbed a external style sheet (and not at the end of head, just where the JS code is thats where the CSS should go)
Thanks!
getElementsByTagName does not accept CSS selector syntax. You're looking for querySelectorAll but you'll have to iterate over the returned list to assign the style, and it's not completely supported across browsers.
...which is why everyone uses jQuery.
Example, assuming you want to modify just the first matched element:
document.querySelectorAll(".mainclass .secondaryclass div td")[0].style.color = '#ffffff';
Note the change from : to =, and wrapping the color value in quotes. JavaScript has different syntax from CSS; I suggest that you take some time to learn it.

Modify dynamically created jQuery checkbox button's css

I'm creating a series of jQuery checkboxes in a loop like so:
var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id);
panel.append(checkbox);
panel.append($('<label>').attr({for: checkbox_id}).html(checkbox_name);
checkbox.button();
I have a css class called my-style that defines things like border-radius, padding, and line-height. I want my-style to override the attributes defined by jQuery's theme for only the checkboxes I've created.
I tried checkbox.addClass("my-style"); and panel.find(".ui-button-text").addClass("my-style"), but neither works correctly. Some css attributes do overwrite jQuery's default values, like border-radius, and others don't ever seem to be able to be overwritten like line-height and padding. I even tried to enforce css attributes directly by panel.find(".ui-button-text").css("line-height", 1.0);, but that doesn't work at all.
I understand that I could just modify the jQuery theme directly by changing the css code in there, but doing so would affect all buttons made, which is not what I'd like to do.
UPDATE:
One way I've managed to address this issue is by specifying the style tag directly. So the code above becomes:
var checkbox = $('<input>').attr({type: 'checkbox',
id: checkbox_id});
panel.append(checkbox);
var label = $('<label>').attr({for: checkbox_id,
style: "font-size: 0.6em; border-radius: 0px; margin-right: 0.3em;"}).text(checkbox_name);
panel.append(label);
checkbox.button();
label.children().attr("style", "padding: 0.2em 0.4em;");
While this solution works, it's unsavory, as I'm mixing JavaScript and CSS code together.
By writing in the style attribute, I can override jQuery UI's CSS. One thing that's been discussed here is using more specific CSS selectors that will be given more weight than jQuery UI's CSS classes. A more specific selector would be something that has the checkbox's ID. The problem with this approach is that checkboxes are dynamically generated, and thus so are checkbox IDs. It's therefore not feasible to have more specific CSS selectors from what I understand.
Is the problem that the class isn't getting applied to the element, or that the class isn't doing what you want it to do?
If the latter, can you paste the css code for your class?
It sounds like your CSS selector is not specific enough, you have two options here
Be nasty and declare your CSS properties with !important to override anything else selected
Write a more specific CSS selector
The latter is the better option, as you will have more control over your styling at a later stage. In case you don't know much about CSS selectors take a read of this (http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html) which should help understand writing more specific selectors and the value of each selector type.

JavaScript & copy style

I am copying a table cell with javascript.
It works fine, just that it doesn't copy the style.
I wanted to copy like below, but that didn't work.
newCell.style=oldCell.style;
So I figured that for my text-align, I have to copy it like this:
newCell.style.textAlign=oldCell.style.textAlign;
That worked, but whenever I add a new style item, I have to remember to register it here.
So, my problem now is how can I loop over the style and copy every item in there?
With chrome, I managed to do it like this:
var strAttribute = GetDomNameFromAttributeName(oRow.cells[1].style[0]);
var styletocopy = eval('oRow.cells[1].style.'+strAttribute);
eval("newCell.style."+strAttribute+"='"+styletocopy+"'"); // //newCell.style.textAlign='center';
But that doesn't work with IE. Haven't tested it with FF, but assume chrome compatibiity.
Is there any way to loop over the style elements in IE?
Or is there any better way to copy all style elements?
eval('oRow.cells[1].style.'+strAttribute)
Never use eval like this(*). In JavaScript you can access a property whose name is stored in a string using square brackets. object.plop is the same as object['plop']:
to.style[name]= from.style[name];
(*: never use eval at all if you can help it. There are only a few very specific and rare occasions you need it.)
Is there any way to loop over the style elements
The style object is supposed to support the DOM Level 2 CSS CSSStyleDeclaration interface. You could loop over the rules and apply them to another element like this:
for (var i= from.style.length; i-->0;) {
var name= from.style[i];
to.style.setProperty(name,
from.style.getPropertyValue(name),
priority= from.style.getPropertyPriority(name)
);
}
in IE?
No, IE does not support the whole CSSStyleDeclaration interface and the above won't work. However there is a simpler way not involving looping that will work on IE and the other browsers too:
to.style.cssText= from.style.cssText;
As simple as that! IE doesn't quite preserve the CSS text the way it should, but the difference doesn't matter for simple inline style copying.
However, as Pikrass said (+1), if you are copying a whole element and not just the styles, cloneNode is by far the most elegant way to do that.
You can copy a DOM Element with all its content (including attributes) with .cloneNode(true) :
var clonedTr = document.getElementById('id').cloneNode(true);
Then clonedTr is an exact copy of the tr #id.
The "true" means you want to copy the content of the element.
To copy all style elements from one node to another you can use
newCell.setAttribute('style', oRow.cells[1].getAttribute('style'))

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

How can I set a css ":hover" on a DOM created element in JavaScript?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).
I'd like to create a hover effect on some of the elements.
example:
#myDiv:hover { background:#000000; }
Is there a way to define that in the DOM? Or do I have to use mouseover?
You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.
I've got a wrapper function lying around which works around some of them; using it, the code would read
document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');
you may create element with predefined class:
.h:hover{color: #c00}
var elem = document.createElement('div');
elem.className = 'h'

Categories