<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?
The function is deleting itself with
It replaces the value of the
votevariable in the outside scope (was the function, is now a number).You could prevent it with a
varkeyword but you should not use twice the same name as it breaks readability.