I have a CSS class defined, call it:
<style type="text/css">
.Foo { position: fixed; left: 50px; top: 50px; }
</style>
where I position an element on the screen absolutely. Throughout my web page's execution, I create and delete many elements and give them class Foo
. When I resize the browser, I want to change the left
and top
values on the Foo
class so the position of all Foo
elements is changed as a result of a calculation.
I don't want to simply change stylesheets, I want to calculate a value and make all current and future Foo
elements have that new calculated left
and top
value.
This site has an example, but the code's quite complex. http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
Is there a good, clean way to basically programmatically alter what Foo
is defined as?
Thanks!
With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties.
To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)
I think this is what you want:
<script>
var style;
function changeFoo(left, top) {
if(typeof style == 'undefined') {
var append = true;
style = document.createElement('style');
} else {
while (style.hasChildNodes()) {
style.removeChild(style.firstChild);
}
}
var head = document.getElementsByTagName('head')[0];
var rules = document.createTextNode(
'.Foo { left: ' + left + 'px; top: ' + top + 'px; }'
);
style.type = 'text/css';
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
if(append === true) head.appendChild(style);
}
</script>
This code was modified from an answer provided in this question which is very similar to what you asked. Whenever you need to change the position of all .Foo elements, you can just call changeFoo(newLeftValue, newTopValue); - the first time around it will create the <style>
element and add it to the <head
> of the document. Subsequent calls will just empty the <style>
element that was already added and add the new rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With