SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jan 2011
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how to change the background colour if a paragraph on click on that paragraph

    I am trying to change the background of a paragraph when the text on that paragraph is clicked.

    The code looks like:

    p= document.createElement("p");
    p.onclick = function(){ p.setAttribute("style","background:#306EFF; " ) ; } ;

    However it will not work.

    What changes should I do in order to make it work?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    When the event triggers the function, it doesn't know anything about the p variable.
    Instead, you can use the this keyword, which refers to the element that triggered the event, that being in this case the paragraph.

    this.setAttribute(...);

    Or, you can directly set the style attribute:
    this.style = '...';
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict bronze trophy AllanP's Avatar
    Join Date
    Sep 2010
    Location
    Australia
    Posts
    298
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I have added a target div so that you can append the paragraph to an existing node on the page.

    Code :
    <!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
     
    <head>
     
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Add attributes to paragraph</title>
    <script type="text/javascript">
    <!--
    window.onload= function() { 
    // create paragraph 
       var para=document.createElement("p");
       var txtNode=document.createTextNode("This is my paragraph. Click me");
       // add text node
       para.appendChild(txtNode);
       // add onclick handler
       var styleString="background-color:#306EFF; cursor:pointer; color:#FFF; font-weight:bold;";
       para.onclick = function(){ para.setAttribute("style",styleString) }
       // get target object
       var targDiv=document.getElementById("myDiv");
       // append new paragraph
       targDiv.appendChild(para);
     }
    // 
    //-->
    </script>
    </head>
     
    <body>
     
    <div id="myDiv">
    </div>
     
    </body>
     
    </html>

  4. #4
    SitePoint Member
    Join Date
    Jan 2011
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot for replays, I got it working.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •