Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript make a function only work once

I'm working on a blog theme where you can like posts from the theme page. It uses the following javascript to like the post with the tumblr API, change the white heart to a red heart, and also +1 to the post note count, displayed above the like buttons. It works fine, but I have the problem that when you click the heart button, it turns red, likes the post, and +1's to the note count, but you can continue to click the button once it's already liked and it keeps adding one to the note count. Can anyone help me to make it so it's a function that only works once, ex: someone clicks the heart button, it turns red, adds one to the note count, and then is done.

$(function() {    
        $('.likepost').live('click', function() {
            var post = $(this).closest('article');
            var id = post.attr('id');
            var oauth = post.attr('rel').slice(-8);
            var count = parseInt($("#note_count_"+ id).text());
            var like = 'http://www.tumblr.com/like/'+oauth+'?id='+id;
            $('#like-it').attr('src', like);
            $(this).css({"background" : "url(http://static.tumblr.com/uiqhh9x/JYdlzwvnx/like2.png)"});
            $("#note_count_"+ id).text(count+1);
            return false;
        });
    });

It's functioning on http://blog.jamescharless.com/, by the way. You have to be logged into tumblr for the script to work.

like image 831
James Charless Dickinson Avatar asked Sep 26 '26 21:09

James Charless Dickinson


1 Answers

$("body").one("click", ".likepost", function() {
//your code here
});

By using the .one() function you only allow the click to be triggered one time. It's kind of what it was designed for. Ideally you'd want to use a parent of .likepost closer to it than the body, but worst case you could just use body as the parent.

like image 147
j08691 Avatar answered Sep 29 '26 10:09

j08691