Using jQuery to Implement Car Turn Signals (Blinkers)

Recently, I've been faced with an unusual challenge. I need to incorporate car turning lights functionality into my website. Specifically, I have to create a scenario where clicking either the left or right button triggers the corresponding green arrow to blink, mimicking a car's turning signals. The tricky part is figuring out how to manage the button's state and make sure the animation behaves as expected. Any insights on how to tackle this would be greatly appreciated. Thank you!

$("#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
    }
}

Answer №1

To maintain the state across multiple clicks, it is recommended to use a closure. You can achieve this by encapsulating the click handler inside a self-invoking function and initializing shared variables within it. Make sure to increment your count at the end of each click. The modulus operator '%' can be used to toggle between true and false values. For example, 0%2==0, 1%2==1, 2%2==0, 3%2==1, 4%2==0, and so on.

(function(){
    var counter = 0;
    $("#arrow-left").click(function blinker() { 
       if(counter%2) {// The modulus operator will switch between 0 and 1, representing true or false
         $('#arrow-left-blink').css("visibility", "visible");
         $('#arrow-left-blink').fadeOut(500);
         $('#arrow-left-blink').fadeIn(500);
         setInterval(blinker, 1000);
      } else {
      //hide
      }
      counter++;
   });
})();

Answer №2

To create a blinking effect, consider implementing a JavaScript function with a counter variable. For instance:

$(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");
    }
  });
});

For a working example, you can check out the JSFiddle link: https://jsfiddle.net/o2xb8Lod/.

Answer №3

Creating a custom CSS class to manage fading and blinking using CSS animations is a great approach. Simply use the toggleClass function in jQuery to apply the effect on click events.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stopping repetitive ajax requests

When I click the "load more" button quickly, it ends up loading the same content twice. I'm looking for a way to prevent this from happening. Below is the ajax call I use to load more content: <script type="text/javascript"> function loadmor ...

What is the significance of utilizing jQuery AJAX's #then, #done, and #fail methods in your workflow?

When using jQuery's aJax method, the object passed in contains success and error handling. So, why do additional methods like #then, #done, or #fail still need to be used if these functionalities are already included in the ajax request parameter? ...

Modifying the User Model in Sails.js results in an automatic password update

/** * User.js * * @description :: The User model handles user data, including hash functions for password security. * @docs :: http://sailsjs.org/#!documentation/models */ var bcryptjs = require('bcryptjs'); function hashPassword(values, ...

Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button. The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

Using jQuery to create a script that will transition random images simultaneously within a div

I am currently working on a JavaScript script that will animate 10 images flying into a div, appearing side by side. The goal is to have each image fly in randomly with a unique transition. At the moment, my script is almost complete as I've successf ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

Tips for positioning text underneath an image with HTML and CSS

I'm attempting to align two links below an image as text. The HTML I have works perfectly in Chrome and Firefox, but not in IE, where 90% of our internal users are. Here is the code: <div style="float: right;"><img src="sites/default/files/ ...

Trying to arrange HTML elements in a diagonal configuration while ensuring they are all uniform in size

My goal is to create an attractive splash page with diagonal, circular links that are all the same size. The <p>'s will function as the links, but I'm struggling to figure out how to make them all diagonal and uniform in size. I've ex ...

Applying a filter within an ng-repeat loop to act as a conditional

Is it possible to use the ng-repeat as a conditional in an efficient and optimal way? I am wondering if there is a way for code to be shown only if found selected is true, without having to create a new variable in the back-end. <div ng-repeat="c ...

What is the best way to serialize the file from a form for uploading and storing in a MongoDB database, utilizing Backbone.js, jQuery, and Node.js?

I'm currently working on implementing a file uploader feature that allows applicants to upload their resumes for specific job posts. I've managed to capture all the form values except for the file upload input. How can I successfully upload, seri ...

Leveraging ASCII characters within the .htaccess file

I'm currently working on developing my own local network website and I'm interested in adding password protection to certain parts using .htaccess. However, the guide I've been following mentioned that they need to be saved with ASCII encodi ...

Shifting Data between JavaScript and PHP

At the moment, I am trying to transfer a variable from JavaScript to PHP. This variable is being utilized for Stripe payment processing. I believe AJAX might be necessary for this task? function _goAheadWithCustomerId(c) { console.log('Customer I ...

Adjustable Size with jQuery UI - Resizing Multiple Divs Causes Movement of Adjacent Divs

I've been experimenting with a webpage that consists of a div element containing multiple nested divs and jQuery UI resizable functionality. Essentially, it's a dashboard comprised of individual widgets. My goal is to resize each widget independe ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...

The HTML table printout is missing cells in the first column

Encountered a strange issue with Internet Explorer and Chrome involving a basic HTML table. The table has no layout CSS, 2 columns, no styles, and its width is set to 100%. When attempting to print the table in these browsers, the first cell on the second ...

Guide to setting up a nested vuetify navigation drawer

I am facing a scenario where I have one fixed navigation drawer with icons and another dynamic navigation drawer that should open and close adjacent to the fixed one without overlapping. The current implementation is causing the dynamic drawer to overlap t ...

Unraveling encoded characters in URLs using Node.js

When I try to send a cookie back using res.cookie(JSON.stringify({bar: "baz"}), the value that I get in return is %7B%22bar%22%3A%22baz%22%7D. How can I decode this in a Javascript setting like node.js? ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

Node.js web application encounters ECONNRESET and MongoNetworkError issues

Currently working on a website with Node.js, Express, and MongoDB (MLAB). The code is too long to post here. When I try to access my index page, app.get("/alumniport", (req, res) => { alumni.find((err, theAlumni) => { if (err) { res.redi ...