Utilizing Jquery for independently blinking text counters

Whenever the user presses a button, a message is created and blinks 5 times. However, each time the button is pressed, all previous messages also blink along with the new one. The goal is to make only the new message blink individually 5 times upon each button press.

Sample HTML:

<div id="result"></div>
<button id="but">Click to Blink Message</button>

JavaScript Code:

var counter = 0;
var i = 0;

function blink(selector){
    $(selector).fadeOut('slow', function(){
        $(this).fadeIn('slow', function(){
            if(counter++ <= 5)
                blink(this);
        });
    });
}

$("#but").click(function() {
    i++;
    counter = 0;
    $('#result').prepend("<div class='num'>Number " + i + "</div>");
    blink('.num');
});

View JSFIDDLE Demo

The issue might be that there is only one counter being used for blinking, causing all messages to blink together. How can a new counter be created every time the button is pressed? And how does the blink function differentiate which counter to use? Various attempts have been made without success. Any suggestions?

Answer №1

The reason is that all the additional elements have the same selector class number.

It looks something like this:

$("#but").click(function() {
    i++;
    counter = 0;
    sel = 'num' + i;
    $('#result').prepend("<div class='"+sel+"'>Number " + i + "</div>");
    blink('.' + sel);
});

Answer №2

UPDATE: A request was made to have the old message continue blinking 5 more times. You can see the code for this modification on JSFiddle.

var counter, i = 0;

function blink(selector) {
    for(counter = 0; counter < 5; counter++){
    $(selector).fadeOut('slow').fadeIn('slow');
    }
}

$("#but").click(function () {
    ++i;
    counter = 0;
    $('#result').prepend('<div id="id-' + i + '">Number ' + i + '</div>');
    blink('#id-' + i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
<button id="but">Blink again 1</button>

Answer №3

After some investigation, it seems like the issue lies in my use of a single counter for blinking. This results in all messages blinking together. To address this, I am looking into creating a new counter each time the button is pressed.

To achieve this, I plan on assigning different class names for every button click. By utilizing the deprecated .selector method to target specific elements, I aim to prevent all HTML elements from being updated simultaneously. It's also crucial to avoid using the selector .num:eq(n), as calling .prepend() again could cause existing elements to no longer be at index 0, leading to simultaneous blinking of all elements.

function blink(callback) {
  var sel = $(this.selector);
  if (sel.data().count === undefined) {
    sel.data("count", blink.counter);
  }
  sel.fadeOut('slow', function() {
    sel.fadeIn('slow', function() {
      if (sel.data().count < blink.max) {
        sel.data().count = 1 + sel.data().count;
        callback.call(sel);
        sel.blink(callback.bind(sel));
      } else {
        sel.data().count = blink.counter
      }
    });
  });
}

blink.counter = 0;
blink.max = 5;

$.fn.blink = blink;

var i = 0;
$("#but").click(function() {
  $('#result').prepend("<div class=num-" + i + ">Number</div>");
  $(".num-" + i).blink(function() {
    $(this).append($(this).data().count)
  });
  ++i;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="result"></div>
<button id="but">Blink again 1</button>

Check out the code snippet on jsfiddle here.

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

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

Switch a div to a computed location

I'm having trouble getting this code to animate a div to a calculated position. Can someone please help me troubleshoot? $(document).ready(function() { var is_Clicked = false; $("#togglebutton").click(function() { if (is_Cli ...

Angular 4 allows the addition of an image from right to left upon clicking

I've been working on angular 4 and I've successfully implemented the functionality of adding flags. However, the issue is that the flags are currently appearing from left to right. What I'm aiming for is to have the images appear from right ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Visual Composer in WordPress is not displaying as expected

I've attempted to uninstall and reinstall Visual Composer, but I'm unable to resolve the issue. I can't edit the front end because it's not displaying properly. I'm using the Ken theme. When checking the console, I encountered this ...

The vertical menu was added, but the text did not align properly

I pasted a sidebar from a different source https://i.stack.imgur.com/jkYWz.png My goal is to have the text appear at the top of the page, similar to this example https://i.stack.imgur.com/1aR5s.png After adding this line, my text is displaying at the b ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

Mastering the art of creating an authentic carbon fiber CSS background

Authentic carbon fiber consists of a series of interconnected grey fibers that resemble woven sheets in grey color. Does anyone have knowledge on how to replicate this pattern using CSS? The examples created by Lea Verou do not accurately depict true carb ...

Error in saving webpage as HTML

I have integrated FileSaver.js into my project to enable users to save web pages as HTML. The code below is triggered when a user clicks on the download button: var originalstr=$.ajax( { type: "GET", url:"url", async: false }).resp ...

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

Creating a PHP script to generate JSON data for fullcalendar integration

I need assistance with creating a PHP script to display the JSON string below: { id:1, start:"10:00", end:"12:00", dow:[1,4], ranges[{start:"2015/03/01", end:"2015/04/01"}] } I am specifically looking for guidance on how to extract and display the &apo ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Changing an HTML file formatted with Jquery into a Phonegap compatible version

I am working on converting my HTML file into an Android app using phonegap. However, I have encountered an issue where the buttons for showing/hiding images using JQuery have stopped functioning properly. Despite linking both the normal jQuery file and th ...

Combine a string and integer in JavaScript without using quotation marks between them

Is there a way to concatenate a string and an integer in JavaScript without getting the ": Here is the code snippet: "<agm-map latitude=" + response.latitude + " longitude=" + response.longitude + "></agm-map>"; What it currently results in: ...

Error Occurs: 'PRM_MissingPanel' randomly in Ajax Update Panel

When using the Ajax Update Panel in Visual Studio to handle post backs for my search function, I encounter an issue. After generating a gridview with the results (i.e., searching for a member), whenever I update to the newest version from TFS, an error is ...

Failure to retrieve the value in a variable using JsonQuery in Python

I am fairly new to utilizing Python within AWS Lambda, and I have spent some time attempting to retrieve a value into a variable using JSON. In my function, I am making an external API call to . However, when trying to fetch the TenantId from the root item ...

Prevent Second Division from wrapping around floated Division

I am running into a minor issue with the positioning of a div in my current project. +------------------------+ |+-------+ ~~~~ TITLE| <--how can I prevent text from wrapping around || | ~~~~~~~~~~~~~ |\ on the left ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

What is the best way to send variables through an HTTP post from a JavaScript function in one file to a separate Python function in a different location?

I have a JavaScript script that retrieves user inputs from my HTML session storage and sends them to a database. Additionally, I need to send a HTTP request to pass a JSON object containing the entries to a Python file hosted elsewhere. Can anyone suggest ...