Jon Jon - 4 months ago 6
HTML Question

Turning jquery into an includable, callable function

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!

I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.

This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.

<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>


<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});

$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>


Since moving the jquery include to the bottom of the page this naturally doesn't work.

What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.

Any help would be greatly appreciated. I'm running out of hair!

Answer

I think, repeated codes will hurt your page than placement of JQuery file.

You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.

$('[id^=comment-vote]").click(function() {
    var elementId = $(this).attr('id');
    var elementIdParts = elementId.split("-");
    var voteType = elementIdParts[2]; 
    var id = elementIdParts[3]; 
    $.ajax({
        type: "GET",
        url: "/ajax.php",
        data: "a=rv&v="+id+"&d="+voteType,
        success: function(data){
            $("#voterow-"+id).text("Thank you for your vote")
        }
    });
    return false;                 
});

$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.

I didn't try the code but the idea behind that would be beneficial for you.

Comments