Reputation: 77
I've got this script in my header and this piece of code in my index, inside the post loop:
$(function() {
var score = parseInt($('.post-score').text().trim());
var color = '#de1d1d';
if (!isNaN(score)) {
if (score >= 5) {
color = '#b84e1f';
}
if (score >= 7) {
color = '#26b81f';
}
if (score >= 9) {
color = '#d9e019';
}
if (score >= 10) {
color = '#0cf';
}
$('.post-score').css('color', color);
}
});
<?php if( in_category( 'reviews') ) : ?>
<div id="post">
<span class="post-score">
<?php the_field('customfield'); ?>
</span>
</div>
<?php endif; ?>
This function changes that custom field text color depending on the number outputted and it is actually working fine, but just once. It's only working for the FIRST POST with a review, and not in every post.
What's wrong with my code?
Upvotes: 0
Views: 196
Reputation: 546
That JQuery code is likely only executed once. But you can achieve the same with PHP.
<?php if( in_category( 'reviews') ) :
$score = get_field('customfield');
$score_color = '';
if($score >= 5 && $score < 7) $score_color = 'b84e1f';
elseif($score >= 7 && $score < 9) $score_color = '26b81f';
elseif($score >= 9 && $score < 10) $score_color = 'd9e019';
elseif($score >= 10) $score_color = '0cf';
?>
<div id="post">
<span class="post-score" style="color: #<?php echo $score_color; ?>">
<?php the_field('customfield'); ?>
</span>
</div>
<?php endif; ?>
You may want to use seperate CSS classes instead of the style-attribute.
Upvotes: 1
Reputation: 2815
Try jQuery each: https://api.jquery.com/each/
Right now, your code is only looking at the first .post-score
that it finds.
Edit: I've got it working for you here on this fiddle - https://jsfiddle.net/8b53j2ah/1/
Upvotes: 1
Reputation: 496
you could set up a function including the above javascript and then run it under the onchange attribute. Eg. onchange="function()"
Upvotes: 0