Jump to content

JavaScript to change properties of a CSS class


chiprivers

Recommended Posts

I would like to be able to change the style within a CSS class using JavaScript.

 

For example, I have several blocks of text in my script, each block is styled using the class 'sometext'.  The 'sometext' class is detailed in a seperate CSS file called 'stylesheet.css'.  Amongst other things, lets say that font-color is set to be red within the class 'sometext'.

 

I want to be able to write a JavaScript command which will change the font-color value to blue for the class 'sometext'.  Changing this value should then effect the styling of the text for all elements with the class 'sometext'.

 

 

Link to comment
Share on other sites

you can probably dynamically write a style tag with custom styles inside..

 

for example..

 

document.write("<style type='text/css'>.someclass { font-size: 32px !important; }</style>");

 

!important will tell the browser to make that declaration more important than any other declaration of same name for any element affected by the css block :)

 

then you can just rewrite the style tag as needed..

 

for example

 

<script type="text/javascript">
fontSize = 12;
function increaseSize(className) {
  fontSize++;
  code = document.getElementById('codeHolder');
  code.innerHTML = "<style type='text/css'>"+
    className+" { \n  font-size: "+fontSize+'px !important;\n}'+
  "</style>";
}
</script>
<div id="codeHolder"></div>
<div class='piss'>TEST ME!</div>
<div><a href='javascript:increaseSize(".piss");'>Increase Size</a></div>

 

Note: Untested.. but I don't see why it wouldn't work :)

Link to comment
Share on other sites

Russell, no offense man, but that's probably the worst way to do it.  JavaScript allows one to dynamically alter an element's CSS on the fly.  Why write directly to the DOM when you can simply play with CSS attributes?

 

To the OP: the problem has two components - grabbing a hold of all the elements of a certain class, then changing their CSS attributes once you have them.  The easiest way to do both is to use jQuery.  It's selector engine saves one from having to worry about those browsers that don't implement a getElementsByClassName function.  To get jQuery and read it's documentation, go to: http://jquery.com

 

So, with that out of the way, something like:

 

$('.sometext').each(function(){
   $(this).css('color', 'blue');
});

 

Should do the trick.

 

Keep in mind, that solving this problem does not require jQuery to work.  It's just the simplest way to go about it.  You could do the same thing in vanilla JavaScript.  It would merely require you to do the heavy lifting of looping through elements to find the right class name, then looping through them again to apply the new CSS rule.

Link to comment
Share on other sites

Russell, no offense man, but that's probably the worst way to do it.  JavaScript allows one to dynamically alter an element's CSS on the fly.  Why write directly to the DOM when you can simply play with CSS attributes?

 

To the OP: the problem has two components - grabbing a hold of all the elements of a certain class, then changing their CSS attributes once you have them.  The easiest way to do both is to use jQuery.  It's selector engine saves one from having to worry about those browsers that don't implement a getElementsByClassName function.  To get jQuery and read it's documentation, go to: http://jquery.com

 

So, with that out of the way, something like:

 

$('.sometext').each(function(){
   $(this).css('color', 'blue');
});

 

Should do the trick.

 

Keep in mind, that solving this problem does not require jQuery to work.  It's just the simplest way to go about it.  You could do the same thing in vanilla JavaScript.  It would merely require you to do the heavy lifting of looping through elements to find the right class name, then looping through them again to apply the new CSS rule.

 

you're talking about jquery..

 

and what do you think jquery does.. it does the whole loop for you.. its still doing the loop.. instead, my solution modifies 1 div, no offense to you but your solution seems just as simple as mine, except yours does more work than mine will :)

 

sometimes a couple lines of code extra will work better than 1 line of jquery, lines don't matter its efficiency :)

 

and PLUS.. your jQuery solution will modify each matched element on the page.. so you're basically adding more characters to the page than mine does aswell..

 

I'm adding a style tag and some class declarations.. you're adding

 

style="xxxxx: whatever; xxxxxx2: whatever;" to each matched element.. its not the most horrible way to do it, its just better than anything you've ever seen ;) thanks :)

Link to comment
Share on other sites

Thanks for the alternative approaches offered.  Maybe a little more detail about what I am trying to do will explain why I need to be able to do this and you can suggest the best approach.

 

I would like to be able to display a list of information drawn from my database.  The list will refresh periodically and update with any newly added records to the database.  When a new item is added to the list, I would like to be able make the text flash to bring it to the attention of the user.  There will be a button next to the new items which the user can use to acknowledge the new entry; once acknowledged, the list entry will no longer flash.

 

I have googled scripts for flashing text and found a couple of approaches: one involving a css statement to set the text to blink but I believe this is not compatible with all browsers, nor does it give me the flexibility I am looking for in my styling; the second method was a javascript function which would run on page load and change the class of an element, however this function had to reference a specific element id.

 

The approach I thought would be easiest would be to have a class set of, lets call it 'flash', and apply this class to any element that I want the text to flash.  Then have a javascript function that would change the font colour parameter of this class every second, alternating between two colours.  This changing the text colour of any element where the class has been applied.

 

To do this, I need to be able to use javascript to reference the font-color property of a class and change it's value.

 

Hope this makes sense and gives you a better idea of what I am trying to do.  Maybe somebody will have an easier approach!?

Link to comment
Share on other sites

Here you'd be better off using jQuery than writing a recursive function to scour the page for elements with 'flash' as their className :)

 

this would do what you want..

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<style type="text/css">
.flash {
color: black;
}
.flash1 {
color: blue !important;
}
.flash2 {
color: purple !important;
}
.flash3 {
color: green !important;
}
</style>
<script type="text/javascript">
var flashes = ['flash1','flash2','flash3'];
var flashInterval = 200; /* in MS */
var originalClassName = '';
var elements;
var timeout;
function nextFlash(num) {
	if (++num > flashes.length) { num = 1; elements.attr('class',originalClassName) }
	timeout = setTimeout("nextFlash("+num+")",flashInterval);
	elements.toggleClass(flashes[num-1]);
}
function startFlash(className) {
	originalClassName = className;
	elements = $('.'+className);
	nextFlash(0);
}
function stopFlash() {
	clearTimeout(timeout);
	elements.attr('class',originalClassName);
}
</script>
<div class="flash">HEY WATSUP</div>
<a id="start" href="#" onclick="startFlash('flash');$(this).hide();$('#stop').show();">
Start Flash!
</a><a style="display: none;" id="stop" href="#" onclick="stopFlash();$(this).hide();$('#start').show();">
Stop Flash!
</a>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.