2
<script type="text/javascript">
        function vote(element, val){
            prev_vote=0;
            vote = 100
            can_vote = element.find('.vote-permission').attr('value')
            alert(can_vote);
            if (can_vote=='yes'){
                if (prev_vote==0){ 
                    alert("previous vote is 0");
                    // user has not cast vote for image before
                    vote_score = vote + val;
                    element.find('.vote-count-post').text(vote_score);
                }
                else if (prev_vote != 0){
                    // user has cast a vote before
                    if (prev_vote == 1 && val == -1){
                        vote_score = vote - 2;
                        element.find('.vote-count-post').text(vote_score);
                    }
                    else if (prev_vote == -1 && val == 1){
                        vote_score = vote + 2;
                        element.find('.vote-count-post').text(vote_score);
                    }
                }
            }
        };

        $(document).on('click', '.votedown', function(e){
            alert($(e.target).prev().text());
            vote($(e.target).parent(), -1);
            alert('vote down is done');
            });

        $(document).on('click', '.voteup', function(e){
            $(e.target).css('background-position', '0 -222px');
            vote($(e.target).parent(), 1);
            alert('vote up is done');
            });
    </script>

The above javascript functions are scaffold for an up and down voting system I am implementing. When a click is made to the upvote or downvote button for the first time the functions execute as expected with vote() called but on a second click the vote() function is said to be not defined. Any ideas why?

1 Answer 1

7

The function is deleting itself with

vote = 100

It replaces the value of the vote variable in the outside scope (was the function, is now a number).

You could prevent it with a var keyword but you should not use twice the same name as it breaks readability.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for that. that pretty much solved it. But just to say. the scoping rules are pretty not friendly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.