How to do car turn lights (blinkers) with jQuery?

299 views Asked by At

I have some strange task to do. I have to implement car turning lights functionality into my web page. I have two buttons (left and right) and two green arrows (left and right). It should be that: I click left button (left arrow is now hidden) and left arrow should blink. When I click once more time, it should stop animation and be hidden. I just don't know to handle state of button and use it properly. Thanks.

$("#arrow-left").click(function blinker() { 
    if(something) {
       $('#arrow-left-blink').css("visibility", "visible");
        $('#arrow-left-blink').fadeOut(500);
        $('#arrow-left-blink').fadeIn(500);
        setInterval(blinker, 1000);
    } else {
     //hide
    }
}
3

There are 3 answers

2
Brent On BEST ANSWER

I would create a css class to handle the fading and blinking with css animations and just toggleClass on click in Jquery.

1
Swimburger On

You should create a closure to save the state across different clicks. Simply create a closure by putting the click handler inside a self-invoking function and declare+initialize your shared variables inside it. Increase your count at the end of the click handler. You can toggle between true and false with the modulus operator '%'. 0%2==0, 1%2==1, 2%2==0, 3%2==1, 4%2==0, ...

(function(){
    var counter = 0;
    $("#arrow-left").click(function blinker() { 
       if(counter%2) {// modulus operator will toggle between 0 and 1 which corresponds to truthy or falsy
         $('#arrow-left-blink').css("visibility", "visible");
         $('#arrow-left-blink').fadeOut(500);
         $('#arrow-left-blink').fadeIn(500);
         setInterval(blinker, 1000);
      } else {
      //hide
      }
      counter++;
   });
})();
1
boroboris On

You could define an outside variable counter. For example:

$(document).ready(function() {


  var counter = 0;
  var blinking;

  function blinker() {
    $('#arrow-left-blink').fadeOut(500);
    $('#arrow-left-blink').fadeIn(500);
    blinker();
  }

  $("#arrow-left").click(function() {
    counter++;
    if (counter % 2 == 1) {
      $('#arrow-left-blink').css("visibility", "visible");
      blinking = setTimeout(function() {
        blinker();
      }, 1000);
    } else {
      clearInterval(blinking);
      $('#arrow-left-blink').css("visibility", "hidden");
    }
  });
});

Here is a JSFiddle link: https://jsfiddle.net/o2xb8Lod/.