Solved

Add a Style Attribute to Div using Javascript function

Posted on 2009-05-19
4
7,914 Views
Last Modified: 2012-05-07
Hi All,

I have a DIV  container and I would like to be able to add ...style="background:#color"... through a javascript function of which the background colour is passed in as a argument..

function OpenDialog(strColour)
{
 Apply background style to MyDivId.
}

Many thanks,

Rit
0
Comment
Question by:rito1
  • 2
4 Comments
 
LVL 40

Accepted Solution

by:
Richard Quadling earned 250 total points
ID: 24426484
Are you using a JS library? I use Prototype (http://prototypejs.org).

Using prototype, I would do ...

$('MyDivId').style.backgroundColor=strColor;

NOTE: strColor needs to be look like #aabbcc where aa, bb, cc are the hex values for the RGB colours.


0
 
LVL 19

Assisted Solution

by:Albert Van Halen
Albert Van Halen earned 250 total points
ID: 24426696
No need for libraries. Although it makes life much easier (my personal fav is jquery)
document.getElementById(myDivId).style.backgroundColor = strColor; // strColor being #rrggbb like RQuadling said (#ff0000 for red) or a named color like : red
 
via jQuery:
$("#" + myDivId).css("backgroundColor", strColor); 

Open in new window

0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 24426752
Albert is right about the libs. But I just find them so useful for consistency and provide some support for features lacking on older browsers.
0
 
LVL 1

Author Closing Comment

by:rito1
ID: 31583232
Thanks both. Much appreciated.

Rit
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now