Background changing depending on title.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • the grim axel
    New Member
    • Mar 2008
    • 3

    #1

    Background changing depending on title.

    I'm trying to write a code that will use css to change the background of a page dependent on the page title. The image used for the background has the same title as the page. I was trying to use the document.write code to write a css tag that sayed
    Code:
    <style>#content{background-image:url(images/{imagenamehere}.jpg);</style>
    Can anyone help me with this?
  • the grim axel
    New Member
    • Mar 2008
    • 3

    #2
    The javascript I have so far is as follows.
    Code:
    function background(){
    var name = document.title;
    var code = "<style>#content{background-image:url(/images/" + name + ".jpg);background-repeat:repeat-y;background-position:right;background-attachment:fixed;</style>";
    document.write(code);}
    This is inside a script tag in the header and I call the background() function onLoad. Can someone tell me what I'm doing wrong?

    Comment

    • mrhoo
      Contributor
      • Jun 2006
      • 428

      #3
      Why don't you use a css style element in the page for this?

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        You can't use document.write after the page has loaded, because the document is closed for writing.

        mrhoo's suggestion is the correct way of solving this, e.g.
        Code:
        var code = "<style>#content{background-image:url(/images/" + name + ".jpg);background-repeat:repeat-y;background-position:right;background-attachment:fixed;</style>";
        becomes [code=javascript]var content = document.getEle mentById("conte nt");
        content.style.b ackgroundImage = "url(/images/" + name + ".jpg);";
        content.style.b ackgroundRepeat = "repeat-y";
        // background-position = style.backgroun dPosition, background-attachment = style.backgroun dAttachment[/code]

        Comment

        • the grim axel
          New Member
          • Mar 2008
          • 3

          #5
          Thank. I didn't know you could access the CSS styles from javascript.

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Originally posted by the grim axel
            Thank. I didn't know you could access the CSS styles from javascript.
            See what you can change.

            Comment

            Working...