jquery – flip image in every 5 sec-ThrowExceptions

Exception or error:

I am fliping the images on mouse over. i want to flip images in every 5 sec automatic. i am new in javascript. so any one can help me it will be great

 #f1_container {
   position: relative;
   margin: 10px auto;
   width: 450px;
   height: 281px;
   z-index: 1;
 }
 #f1_container {
   perspective: 1000;
 }
 #f1_card {
   width: 100%;
   height: 100%;
   transform-style: preserve-3d;
   transition: all 1.0s linear;
 }
 #f1_container:hover #f1_card {
   transform: rotateY(180deg);
   box-shadow: -5px 5px 5px #aaa;
 }
 .face {
   position: absolute;
   width: 100%;
   height: 100%;
   backface-visibility: hidden;
 }
 .face.back {
   display: block;
   transform: rotateY(180deg);
   box-sizing: border-box;
   padding: 10px;
   color: white;
   text-align: center;
   background-color: #aaa;
 }
<div class="work">
  <a href="inner.html">
    <div id="f1_container">
      <div id="f1_card" class="shadow">
        <div class="front face">
          <img src="img/work1.jpg" class="bottom" alt="" />
        </div>
        <div class="back face center">
          <img src="img/work2.jpg" class="top" alt="" />
        </div>
      </div>
    </div>
  </a>
</div>

on mouse its working fine . but i want auto flip in every 5 sec

How to solve:

You should be using setInterval()

window.setInterval(function() {
    // Function goes here
}, 5000);

It loops a function every 5000 milliseconds.


In your situation you’re already using :hover to change the css, change this :hover to a class. Now you can toggleClass() on an object with jQuery, so it gets removed if it’s there, and added if it’s not there.

This CSS

#f1_container:hover #f1_card {
  transform: rotateY(180deg);
  box-shadow: -5px 5px 5px #aaa;
}

Becomes:

.flipped { 
  transform: rotateY(180deg);
  box-shadow: -5px 5px 5px #aaa;
}

And your jQuery:

window.setInterval(function() { //setInterval (loop a function)
    $("#f1_card").toggleClass("flipped"); //toggle class "flipped"
}, 5000); // Loop it every 5000 milliseconds

JavaScript:

window.setInterval(function() {
    document.getElementById("f1_card").classList.toggle("flipped");
}, 5000)

Every 5000 milliseconds you toggle the class flipped on #f1_card, so that it flips back and forth.


Explanation

Let’s break down what we did, we changed the :hover to a class because instead of making it occur on hover we want to make it occur by toggleClass() every 5000 milliseconds (we use the setInterval() function for this).

Leave a Reply

Your email address will not be published. Required fields are marked *