Add an exciting new element to the array within the DOM using knockout.js

Is there a way to make the font color change to red and then back to white when a new item is added to a play by play array using knockout? I know how to achieve this effect on a single property with the provided binding, but I'm unsure of how to do it for a new object being added to the DOM.

ko.bindingHandlers.flash = {

    init: function (element, valueAccessor) {},

    update: function (element, valueAccessor) {

        var updated = valueAccessor().updated;

        if (updated()) {
            $(element).addClass('flash');
            setTimeout(function () {
                $(element).removeClass('flash');
            }, 1000);

            updated(false);
        }
    }
};

CSS

.flash {
    color: red;
    -webkit-transition: color 0.4s ease;
    -moz-transition: color 0.4s ease;
    -o-transition: color 0.4s ease;
    transition: color 0.4s ease;
}

HTML

<div class="accordion-inner period-play-by-play" data-bind="foreach: plays">
                        <div class="play" data-bind="css: {'home-team': $data.IsHomeTeam, 'away-team': !$data.IsHomeTeam, 'modified': $data.isNew}">
                            <b data-bind="text: $data.Time + ' '"></b>
                            <span data-bind="text: $data.Team + ' ' + $root.actionName($data.Action)"></span> 
                            <span data-bind="text: $root.actionTypeName($data.ActionType)"></span>
                            <span>by <i data-bind="text: $data.Name"></i></span>
                            <!-- ko if: $data.Lead != '' -->
                            <div class="pull-right" data-bind="text: $data.Lead"></div>
                            <!-- /ko -->
                        </div>
                    </div>

Answer №1

Utilize the afterAdd foreach binding to animate newly added elements without the need for creating custom bindings like flash.

For more information, visit Knockout's documentation on foreach binding.

var vm = {
  plays: ko.observableArray([{
    IsHomeTeam: Math.random() >= 0.5,
    isNew: true,
    Time: new Date().toLocaleString(),
    Team: 'default team',
    Action: 'default action',
    ActionType: 'default action type',
    Name: 'default name',
    Lead: Math.random() >= 0.5
  }]),
  actionName(name) {
    return name;
  },
  actionTypeName(name) {
    return name;
  },
  flashAnimate(element) {
    $(element).addClass('flash');
    setTimeout(function() {
      $(element).removeClass('flash');
    }, 1000);
  },
  addNew(vm) {
    vm.plays.push({
      IsHomeTeam: Math.random() >= 0.5,
      isNew: true,
      Time: new Date().toLocaleString(),
      Team: 'new team',
      Action: 'new action',
      Name: 'new name',
      Lead: Math.random() >= 0.5
    });
  }
};

ko.applyBindings(vm);
.play {
  -webkit-transition: color 0.4s ease;
  -moz-transition: color 0.4s ease;
  -o-transition: color 0.4s ease;
  transition: color 0.4s ease;
  display: flex;
  flex-direction: column;
  margin: 10px;
  padding: 10px;
  border: 1px solid;
}

.flash {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="accordion-inner period-play-by-play" data-bind="foreach: { data: plays, afterAdd: flashAnimate }">
  <div class="play" data-bind="css: {'home-team': $data.IsHomeTeam, 'away-team': !$data.IsHomeTeam, 'modified': $data.isNew}">
    <b data-bind="text: $data.Time + ' '"></b>
    <span data-bind="text: $data.Team + ' ' + $root.actionName($data.Action)"></span>
    <span data-bind="text: $root.actionTypeName($data.ActionType)"></span>
    <span>by <i data-bind="text: $data.Name"></i></span>
    <!-- ko if: $data.Lead != '' -->
    <div class="pull-right" data-bind="text: $data.Lead"></div>
    <!-- /ko -->
  </div>
</div>
<button style="margin: 0 10px" data-bind="click: addNew">Add New</button>

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

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Managing JavaScript and AJAX requests in a single thread

Many believe that Javascript is a single-threaded language, while AJAX is considered asynchronous. Imagine this scenario; Let's say there is a button that, when clicked, triggers an AJAX call that takes 5-6 seconds to complete. Despite this, the UI ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

What is the best way to offer compressed files on a webpage for easy extraction by a function and integration with a library?

In the process of creating an application using threejs, I have made sure to optimize my 3D models effectively. However, even after this optimization, the total size of all the models combined still amounts to a significant number like 100-150 Mb without i ...

How to Implement Jquery Confirm in Laravel Form Opening?

I've set up a Form using the Laravel Form package. {!! Form::open(['action' => ['Test\\BlogController@destroy', $thread->id], 'method' => 'delete', 'onsubmit' => 'Confirm() ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

How come ng-click isn't triggering in the components' template?

Embarking on a new Angular project has presented me with some challenges in understanding the basics. One issue I'm facing is getting ng-click events to work properly within my component model. Despite following various solutions from Stack Overflow, ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

What is the best way to have a div gradually glide out (utilizing CSS's transition feature) upon the click of a particular button?

I want the hint-bubble div to smoothly slide out (using 'transition: 0.5s') whenever the hint-btn is clicked. I have successfully implemented it so that the hint-bubble appears when the button is clicked, but it appears instantly and I am struggl ...

The designation is being acknowledged as a <div>

I am facing an issue with a div structure that contains a label and 4 child divs. My goal is to apply CSS and jQuery effects to only the child divs, excluding the label. To achieve this, I implemented the following code: HTML: <div class="score row-fl ...

Slick Slider - Defining the Initial Slide

My website features a dynamic carousel showcasing a basketball team's schedule, with games sorted by date for the current season. I am trying to align the slider to display the upcoming game at the center. How can I designate a specific slide as the ...

What's the best way to trigger useEffect whenever a useRef variable gets updated?

I am facing an issue where the variable changes are lost on every re-render when trying to have useEffect run every time it modifies a variable. Using useRef to store the variable between renders leads to useEffect not detecting changes to a ref. I came a ...

Ion-row appears out of frame

This is a simple layout: <ion-content> <ion-grid *ngIf="loaded"> <ion-row> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> </ion-row> < ...

What is the best way to horizontally align an element within a Material UI Grid item?

How do I align elements in the center of a Material UI Grid item? Check out this code snippet from my React project: <Grid container> <Grid item xs={4}> // Other content goes here </Grid> <Grid item xs={4}> // How can ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

Is there a way to ensure that the images in the slider all remain consistent in size?

I recently created a slider using bootstrap and encountered an issue with image display on mobile screens compared to laptop screens. On a Laptop screen: On a Mobile screen: The images on the mobile screen are not fitting properly within the slider, and ...

Making sure to correctly implement email input fields in HTML5: Surprising behaviors observed with the email input type in the Chrome browser

Within the upcoming code snippet, a basic email validation is implemented. An input field's background color will display as white for valid emails and yellow for incorrect values. This functionality operates seamlessly in Firefox; however, in Chrome, ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

What steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...