Creating reactive evaluation buttons in javascript / html

advertisements

We have an assignment in school to improve project, without actually knowing the programming languages. We got the skeleton of the project and we must add some functionality to it.

The skeleton is a blog, that has a login/register/ and you can create, edit and delete articles.

My first idea is to add two buttons - like and dislike, linked to a variable. Clicking the like button will increase the rating with 1, and dislike will decrease it. I added the buttons but I'm struggling with the javascript code. It should look something like this:

 <script>
     var rating = 0;

     function IncreaseRating() {
         document.getElementById('like').value = ++rating;
     };
     function DecreaseRating() {
         document.getElementById('dislike').value = --rating;
     };
 </script>
 <button id="like" type="button" onclick="IncreaseRating()">Like</button>
 <button id="dislike" type="button" onclick="DecreaseRating()">Dislike</button>
 <script>document.write(rating)</script>

but it is not working. Somehow I managed to display the rating value, but it does not increase nor decrease. How can I solve my problem?


The order of your code is the problem, you run your script tag BEFORE the elements are included in the DOM.

To fix it, just change the order, put the script tag at the very bottom of the document, right before the closing tag.

<button id="like" type="button" onclick="IncreaseRating()">Like</button>
<button id="dislike" type="button" onclick="DecreaseRating()">Dislike</button>
<script>
    var rating = 0;

    function IncreaseRating() {
        document.getElementById('like').value = ++rating;
    };
    function DecreaseRating() {
        document.getElementById('dislike').value = --rating;
    };
</script>

<script>document.write(rating)</script>