Reputation: 2171
I have a jQuery function that swaps an image when it is clicked. This works well, However, I would also like to pass a parameter using $.get depending on which image is being displayed.
Here's the context. I have a bunch of comments and a "thumbs up" image next to each. when the thumbs up is clicked, it turns green and calls a PHP script via the $.get method. this works, but I also want the user to be able to "un-thumbs up" so that if they click one that was already green, then can remove their up vote. Here is what I have so far.
My jQuery:
<script>
$(document).ready(function() {
$('.thumb a').on('click', function(e) {
e.preventDefault();
var $img = $(this).find('img');
var $idshow = $(this).attr("id");
$img.attr('src', function(_,s) {
return s.indexOf('thumbs_up_green') > -1 ? '../images/thumbs_up.png'
: '../images/thumbs_up_green.png'
});
//HERE IS THE VARIABLE I WANT TO BE ABLE TO CHANGE
var $action = "add";
$.get("thumb_up_tip.php?tip_id=" + $idshow + "&action=" + $action)
});
});
</script>
In the above code, if the button is going from "thumbs_up.png" to "thumbs_up_green.png" I want the var $action to be "add". If it is going from "thumbs_up_green.png" to "thumbs_up.png" then I want the var $action to be "subtract".
Any recommendations would be great!
Upvotes: 0
Views: 61
Reputation: 140
When adding or unadding add a class to the element. Then on your click check to see what class exists and then decide your action based off of that.
<script>
$(document).ready(function() {
$('.thumb a').on('click', function(e) {
e.preventDefault();
var $img = $(this).find('img'),
$idshow = $(this).attr("id"),
$action = 'add';
if($img.hasClass('thumbsUp')){
$action = "remove";
$img.removeClass('thumbsUp');
}else{
$img.addClass('thumbsUp');
}
$img.attr('src', function(_,s) { return s.indexOf('thumbs_up_green') > -1 ? '../images/thumbs_up.png' : '../images/thumbs_up_green.png'});
$.get("thumb_up_tip.php?tip_id=" + $idshow + "&action=" + $action)
});
});
</script>
Its going to check if a class exists on the element, if so this is already thumbs up so we should remove and vice versa.
Upvotes: 1