minemindmedia
minemindmedia

Reputation: 409

Refresh div and randomly change text color

I have a div, pulling a random testimonial with a shortcode in WP.

<div id="testimonial-refresh"><?php echo do_shortcode('[random-testimonial]'); ?></div>

I have this script that refreshes the div every 3 seconds.

<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$("#testimonial-refresh").load(location.href+" #testimonial-refresh>*","");
}, 3000);
</script>

I would like to know how I can set 5 colors and have the text color change randomly every time the div refreshes.

I've successfully set this up but it only changes color when the window reloads. I want it to change the color when the div reloads.

Thank you. I've been searching for two hours and have not come up with a solution.

UPDATE

This actually takes care of it, but it's a little glitchy:

<script type="text/javascript">

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];

var auto_refresh = setInterval(function () {
    // load another testimonial
    $("#testimonial-refresh").load(location.href+" #testimonial-refresh>*","");
    // change text color randomly
    var rand = Math.floor(Math.random() * colors.length);
    $("#testimonial-refresh").css('color', colors[rand]);
}, 3000);

</script>

Upvotes: 0

Views: 1440

Answers (2)

sjkm
sjkm

Reputation: 3937

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];
var element = $("#testimonial-refresh");

var auto_refresh = setInterval(function () {
    element.load(location.href+" #testimonial-refresh>*", function() {
        // load performed -> change text color randomly
        var rand = Math.floor(Math.random() * colors.length);
        element.css('color', colors[rand]);
    });
}, 3000);

Update

if you want to use your script, then this should work:

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];

var auto_refresh = setInterval(function () {
    // load another testimonial
    $("#testimonial-refresh").fadeOut(function() {
       $(this).load(location.href + "?ts=" + new Date().getTime() + " #testimonial-refresh>*", "", function() {
            // change text color randomly
            var rand = Math.floor(Math.random() * colors.length);
            $("#testimonial-refresh").css('color', colors[rand]);

            $(this).fadeIn();
        });
    });
}, 3000);

Upvotes: 0

jasonhansel
jasonhansel

Reputation: 642

Within the function, add the following code:

var colors = ["#000", "#00f", "#f00"]; // The list of colors to use
$("#testimonial-refresh").css("color", colors[Math.floor(Math.random()*colors.length)]);

The other answer to this question won't work because it's missing the Math.floor call.

Upvotes: 1

Related Questions