Rob
Rob

Reputation: 1495

Auto refresh div without refreshing the whole page

Is there a simple way to auto refresh a div without refreshing the whole page?

<div class="refresh-this">
  <div class="left">
    Left
  </div>

  <div class="right">
    Right
  </div>
</div>

You'll see in the codepen, I'm adding a random class each time the page refreshes

https://codepen.io/anon/pen/JOjwLz

Upvotes: 0

Views: 773

Answers (1)

acoder
acoder

Reputation: 759

Hi you can use this jquery script.

function randomClass() {

    let classes = ['random-1','random-2', 'random-3'];
    let index = Math.floor(Math.random() * classes.length);

    return classes[index];
}

$(document).ready(function(){
  setInterval(function(){
    let leftClass, rightClass;
    while (leftClass == rightClass) {
        leftClass = randomClass();
        rightClass = randomClass();
    }
    $('.left').addClass(leftClass);
     $('.left').removeClass(rightClass);
    $('.right').addClass(rightClass);
     $('.right').removeClass(leftClass);
    }, 1000);
});

At the last I add 1000 its means every 1 seconds later this div will be refresh. If you want you can change the time. If you have any question feel free for asking me.

Upvotes: 2

Related Questions