Javascipt technical questions

Discussion in 'JavaScript' started by danX, Jul 1, 2013.

  1. #1
    Hi guys! My first post, ever. I have some technical question on JavaScript.
    First I would like to ask why doesn't this code work? I want to change the css style color back and forward after clicking but it doesn't work.
    
    <p id="demo">
    Some text whose color I want to change
    </p>
     
    <script>
    function myFunction()
    {
    x=document.getElementById("demo") // Find the element
    if(x.style.color.match("#000000")) {x.style.color = "#ff0000";}
    else x.style.color = "#000000";
    }
    </script>
     
    <button type="button" onclick="myFunction()">Click Me!</button>
    [code]
    Thnak you in advance!!
    Code (markup):

     
    Last edited by a moderator: Jul 1, 2013
    danX, Jul 1, 2013 IP
  2. malky66

    malky66 Acclaimed Member

    Messages:
    3,997
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #2
    Try this:
    <p id="demo">
            Some text whose color I want to change
            </p>
     
            <script>
            function myFunction()
            {
            x=document.getElementById('demo') // Find the element
            if (x.style.color.match("ff")||x.style.color.match("255")){  // Moz browsers use RGB  'rgb(255,0,0) == red
                x.style.color='#000000';
              }
            else
              {
                x.style.color='#ff0000';          // Change the style
              }
            }
            </script>
            <button type="button" onclick="myFunction()">Click Me!</button>
    Code (markup):
    source: http://www.webdeveloper.com/forum/showthread.php?269759-javascript-question
     
    malky66, Jul 1, 2013 IP
  3. aidanriley629

    aidanriley629 Banned

    Messages:
    429
    Likes Received:
    23
    Best Answers:
    3
    Trophy Points:
    175
    #3
    Your if statements are backwards, I believe. You want to look for black text (default) and change it to red, but the script is trying to find red text and change it to black. #000000=black, ff=red. Switch those around and try it again. Since you aren't using moz elements I don't see how that is relevant. Let us know what happens.

    Also isn't there a semi-colon missing after ("demo")?
     
    Last edited by a moderator: Jul 1, 2013
    aidanriley629, Jul 1, 2013 IP
  4. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,983
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #4
    Not required. They are optional in JS.
     
    ryan_uk, Jul 1, 2013 IP
    malky66 likes this.
  5. aidanriley629

    aidanriley629 Banned

    Messages:
    429
    Likes Received:
    23
    Best Answers:
    3
    Trophy Points:
    175
    #5
    In this case it does not make a difference, you're right, but optional? The formal literature is quite clear in that they are necessary in many cases, and it's considered best practice to just include them for readability even when they are optional. Or at least be consistent--the above code has random semicolons.
    Here's an example:
    The source
    a = b + c
    (d + e).print()
    is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the
    second line can be interpreted as an argument list for a function call:
    a = b + c(d + e).print()
    Code (markup):
    http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf pp.28
    http://inimino.org/~inimino/blog/javascript_semicolons
     
    aidanriley629, Jul 1, 2013 IP
  6. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,983
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #6
    Like you wrote, best practise. Such as it's not best practise to copy and paste someone else's code and then claim it as your own.

    I could provide you with a bunch of links also showing you the pointlessness of semi colons in JavaScript, but I won't because you already provided one. (Read the second link, it's some bloke banging on a lot, but even he states they are inserted automatically. Even what you pasted is about automatic insertion.) The fact is, there is a chance to screw up code by using them.

    I feel all dirty by mentioning inserted and insertion a lot lol!
     
    ryan_uk, Jul 1, 2013 IP
  7. aidanriley629

    aidanriley629 Banned

    Messages:
    429
    Likes Received:
    23
    Best Answers:
    3
    Trophy Points:
    175
    #7
    I'd be happy to take a look at those links. If you know when it's okay to put semicolons, you'll have no problem..whereas if you never put them, you will. They ARE needed sometimes.
     
    aidanriley629, Jul 1, 2013 IP
  8. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,983
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #8
    Yes, if you put semi-colon where it shouldn't be you could end up with broken code. :rolleyes: Or a bunch of pointless line breaks.

    @OP, I recommend you use JSFiddle.net when experimenting with your code. It's a quick and easy way to see end results, but also share the code, too. As an example, here is the code malky66 quoted:
    http://jsfiddle.net/ZSud3/

    And it's changing the colour.
     
    Last edited: Jul 1, 2013
    ryan_uk, Jul 1, 2013 IP
    malky66 likes this.
  9. FilmFiddler

    FilmFiddler Greenhorn

    Messages:
    54
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    23
    #9
    To handle the problem of color detection robustly, something like the following is needed, noting that:
    1. style detection is often not simple. See:
    http://www.quirksmode.org/dom/getstyles.html
    http://www.javascriptkit.com/dhtmltutors/dhtmlcascade.shtml

    2. browsers vary in the way they report a detected color:
    * some report color as hex
    * some report color as rgb
    And there may be subtle variations (in spaces) in the rgb string returned
    * some browsers may report color in whatever format it was originally set in - hex or rgb.

    So therefore, a Regular Expression is needed cover all those bases.
    Some of the code posted previously in this thread will work on the second button click, but not on the first click.
    As discussed in the Quirksmode link, the robust way of detecting styles is to use the more complex method involving getComputedStyle(obj,'').getPropertyValue('color').

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Test Color Detection</title>
    <style type="text/css">
    #demo { color: #000000; }
    </style>
    </head>
    <body>
    <p id="demo">Some text whose color I want to change</p>
    <button type="button" onclick="myFunction()">Click Me</button>
     
    <script type="text/javascript">
    function getColor(obj) {
      if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(obj,'');
        return compStyle.getPropertyValue('color');
      }
      else if (obj.currentStyle) // IE8 and earlier
        return obj.currentStyle['color'];
    }
    function testColorFormat(st) {
      var col = /^(#000000|rgb\(0, *0, *0\))$/i;
      return st.match(col);
    }
     
    function myFunction(){
      x = document.getElementById("demo");
      if (testColorFormat(getColor(x)))
        x.style.color = "#ff0000";
      else
        x.style.color = "#000000";
    }
    </script>
    </body>
    </html>
    Code (markup):
     
    FilmFiddler, Jul 2, 2013 IP
    ryan_uk likes this.
  10. danX

    danX Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #10
    Such a warm welcome! You are good people. I tried it and it worked. Thank you guys
     
    danX, Jul 2, 2013 IP
  11. danX

    danX Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #11
    Hwy it is me againg. I would liek to ask you why does the button disappear after clicking?

    <h1> My webpage </h1>
    <p id = "demo">para para paragraph </p>
    <div id = "myDIV"> A DIV </p>


    <script>
    function myFunction()
    {document.getElementById("demo").innerHTML="Hello Dolly";
    document.getElementById("myDIV").innerHTML="How are you?";
    }
    </script>

    <button type="button" onclick="myFunction()">Click Me!</button>

    </body>
    </html>
     
    danX, Jul 2, 2013 IP
  12. danX

    danX Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #12
    OMG, sorry for bothering you. I got it. :p It was the closing tag of the div element
     
    danX, Jul 2, 2013 IP