Ad

How To Handle Onclick Event Of A Button?

- 1 answer

In the below code,

<!DOCTYPE html>
<html>
    <head>
        <title>Button events</title>
        <meta charset="UTF-8">
        <style type="text/css">
            button{
                background-color: #00FFFF;
                border: 2px solid orange;
                border-radius: 10px;
                width: 60px;
                height: 30px;
                color:white;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
            document.body.lastElementChild.onclick = changeColor;
            function changeColor(){
                if(document.body.lastElementChild.innerHTML == "Like"){
                    document.body.lastElementChild.style.background-color = "#FF9966";
                    document.body.lastElementChild.innerHTML = "Unlike";    
                }else{
                    document.body.lastElementChild.style.background-color="#00FFFF";
                    document.body.lastElementChild.innerHTML = "Like";  
                }
            }
        </script>
        <button type="button" name="LikeUnlike">Like</button>

    </body>
</html>

error is thrown at line document.body.lastElementChild.style.background-color = "#FF9966";. Error is Invalid left-hand side in assignment.

How do I resolve this error?

Note: yet to learn JQuery

Ad

Answer

First of all you need to use element.style.backgroundColor instead of element.style.background-color.

Here is a list of the JS equivalent of CSS attributes.

Your second problem is that your script executed before the <button> is loaded, thus making the script the current lastElementChildof body.

You can solve this by wrapping your script in window.onload:

(Also, selecting your button with document.body.lastElementChild is bound to give you errors since you most likely at some point will add something after the button)

<!DOCTYPE html>
<html>

<head>
  <title>Button events</title>
  <meta charset="UTF-8">
  <style type="text/css">
    button {
      background-color: #00FFFF;
      border: 2px solid orange;
      border-radius: 10px;
      width: 60px;
      height: 30px;
      color: white;
    }
  </style>
</head>

<body>
  <script type="text/javascript">
    window.onload = function() {
      
      var likeButton = document.getElementById("like-button");
      likeButton.onclick = changeColor;

      function changeColor() {
        if (likeButton.innerHTML == "Like") {
          likeButton.style.backgroundColor = "#FF9966";
          likeButton.innerHTML = "Unlike";
        } else {
          likeButton.style.backgroundColor = "#00FFFF";
          likeButton.innerHTML = "Like";
        }
      }
    }
  </script>
  <button type="button" name="LikeUnlike" id="like-button">Like</button>

</body>

</html>

Ad
source: stackoverflow.com
Ad