jQuery:
$(".upvote").click(function() {
var id = $(this).attr('id');
var changeImage = ($(this).children('img').attr('src') === siteUrl + '/images/icon-upvote.png')
? siteUrl + '/images/icon-upvote-inactive.png'
: siteUrl + '/images/icon-upvote.png';
$(this).children('img').attr('src', changeImage);
var changeClass = ($(this).children('img').attr('src') === siteUrl + '/images/icon-upvote.png')
? 'vote-icon'
: 'vote-icon semi-transparent-more';
$(this).children('img').attr('class', changeClass);
$.ajax({
type: 'GET',
data: 'comic=' + id + '&type=upvote',
url: siteUrl + '/vote.php',
success: function() {
// PHP does all checks
}
});
});
HTML:
<div>
<a href="vote.php?comic=$fileName&type=upvote" id="$fileName" class="upvote$guestLink" onclick="return false;">$upvoteImage</a>
</div>
<div style="margin: 5px 0 8px 0;">
<span class="score$scoreStyle bold" id="$fileName">$fileScore</span>
</div>
<div>
<a href="vote.php?comic=$fileName&type=downvote" class="downvote$guestLink">$downvoteImage</a>
</div>
This is what I’ve got and it works really well. Problem is I know there’s a way to make this a tad more efficient than what I have.
Also, how can I select that span to change it’s value? And how would I go about adjusting the value based on what is currently set within it? I’ve been struggling on this for the longest time.
What I’ve changed:
idvariable: given that in the functionthisis the DOM element, you can saythis.iddirectly instead of creating a jQuery object with$(this).attr('id')$(this).children('img')(I’ve created a variable$imgfor this.)?is nice in a general sense, but you were using it twice (once forchangeImageand once forchangeClass) to evaluate the same condition. To me it makes more sense to evaluate that condition once in anifand then set both variables..attr()twice, but you can pass it a map of attributes and change them all at once.Well it would be a little easier to select if it was a child of the same div as the up and down anchor elements, but anyway for your structure maybe something like this:
Note also that you’ve given that span an id that is the same as the id of the anchor element above it – this makes your html invalid because id should be unique on the page. I assume that you can’t select by id though because you have multiple voting elements on the page.
As far as setting the value, to get the current value and increment in JS:
The syntax of passing a callback to
.html()gives you a parameter with the old value and then you return the new value to set. So+oldHTMLconverts the string to a number – obviously I’m assuming here the span contains nothing but a number – and then adds one to it.However, I think it would be better to do that in your ajax success handler using data from the server: have your PHP code return the new value and then in the success handler apply that value.