Creating an endless ticker animation in AngularJS that dynamically adjusts to element dimensions

This is my initial foray into AngularJS, where I am creating a ticker display comprised of boxes.

Check out the CodePen here

The Code:

index.jade:

doctype html
html(ng-app="ticker")
    head
        script(src="../bower_components/angular/angular.js", type="text/javascript")
        script(src="script.js")
        link(rel="stylesheet", href="css.css")
body
    div(ng-controller="tickerCtrl")

        .ticker
            .viewport(ng-class="{moving: moving}", ng-click="moveLeft()")
                .box(ng-repeat="box in boxes")
                    span {{ box.title }}

        button(type="button", ng-click="moveLeft()") < Move left

script.js

angular.module('ticker', [])
    .controller('tickerCtrl', ['$scope', '$window', function($scope, $window) {
        $scope.boxes = [
            {title: 'Box 1'},
            {title: 'Box 2'},
            {title: 'Box 3'},
            {title: 'Box 4'},
            {title: 'Box 5'},
            {title: 'Box 6'},
            {title: 'Box 7'},
            {title: 'Box 8'},
            {title: 'Box 9'},
            {title: 'Box 10'}
        ];
        $scope.moving = false;

        $scope.moveLeft = function() {
            $scope.moving = true;
            $window.setTimeout($scope.switchFirst, 2000);
        };
        $scope.switchFirst = function() {
            $scope.boxes.push($scope.boxes.shift());
            $scope.moving = false;
            $scope.$apply();
        };
    }]);

css.less

.ticker {
    width: 90%;
    padding: 1em 1em;
    height: 100px;
    overflow: hidden;
    position: relative;

    .viewport {
        &.moving {
            animation: moveLeft 1 2s linear;
        }

        position: absolute;
        height: 100px;

        border-width: 1px 0;
        border-style: solid;
        border-color: #cccccc;

        white-space: nowrap;

        .box {
            display: inline-block;
            width: 100px;
            height: 100%;

            border: 1px solid #eee;
            margin: 0 5px;

            text-align: center;
        }
    }
}

@keyframes moveLeft {
    0% { transform: translateX(0) }
    100% { transform: translateX(-110px) }
}

Challenges Faced:

  • How can I achieve continuous movement? Adding

    $window.setInterval($scope.moveLeft, 2000);
    within tickerCtrl only triggers the animation once.

  • Is it possible to dynamically retrieve element dimensions? Currently, the viewport shifts by 110px but ideally should match the first element's outerWidth.

  • Should I continue with AngularJS or switch to jQuery for this task?

Answer №1

UPDATE: Take a look at the solution I provided here -

First off, when working with Angular, it is recommended to use Angular's $timeout instead of setTimeout.

Secondly, if you need repetitive actions, consider using setInterval or in Angular, $interval.

Angular simplifies dom manipulation by providing a lightweight jquery-like code called JQlite, rendering jQuery unnecessary. You can manipulate DOM elements using $element.

Alternatively, you can also work with the javascript DOM API...

document.body.getElementsByClassName('some-class')[0].clientWidth

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

Conceal particular table cells through jQuery

I am a beginner in the world of jQuery. My goal is to hide certain cells in a row when clicked, and have them displayed again when clicked once more. I've searched high and low for a solution, but all I find is how to hide entire rows. Here's an ...

Nodemon is not auto-reloading my server even after I have updated the code

I'm having trouble with nodemon not restarting my file after I make changes to it. It says it's restarting but doesn't actually do it. I've attempted putting the nodemon command into npm start and using the -L flag, but it hasn't s ...

Using setInterval to update the content of a Text Area continuously

I am currently working on a script that involves extracting a string from a textarea, breaking it down into an array using the delimiter "=====\n", and then displaying each element of the array in the textarea every 250ms. However, I have noticed that ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

Does the body element inherit the line height property?

Below is some simple HTML code consisting of a div and a span: <div id="container">Some text to affect the width</div> <span>A</span> I am currently using Eric Meyer's CSS Reset, which sets the line-height of the body to 1 an ...

Could it be that this is a mysterious foreign alphabet or a problem with the encoding?

I'm facing a strange bug with characters on my website and I can't seem to figure out what's causing it. A foreign writer submitted an article to me, and when I received it, the font was displaying oddly. After some investigation, I've ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

Why isn't the float left property working as expected?

Why won't my image float to the left? I'm using a class called align-left with float: left but it's not working. You can see the live version at - (check out the review grid halfway down under the heading 'High customer satisfaction r ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

Checkmate with React Native's Checkbox Component

I have implemented the React Native Elements CheckBox inside List Items within a Flat List. import React, { Component } from "react"; import { View, Text, StyleSheet, FlatList } from "react-native"; import axios from 'axios&apo ...

Dealing with JavaScript errors within an Express application

Consider the following async function export async function fetchData() { const result = await fetchData(); return result[0].id; } In the route, there is router.post( '/some-route', handleAsyncError(async (req: Request, resp: Response, _ ...

Having trouble accessing CSS images in JSF

Issue Details : I am currently facing a problem with setting menu background images in my JSF application using CSS properties. The file structure is as follows This is the CSS snippet Style.css #menu { height:35px; width:950px; backgrou ...

How can I set the value of scope on a click event in Angular?

I'm having trouble creating a toggle feature in my angular project. I can't figure out why it's not functioning properly. My expectation is that when the a-tag is clicked, the lower div should display. <div> ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Is there a way to integrate a JQuery plugin into another plugin seamlessly without causing any conflicts or disruptions?

With the code provided, a flip effect is being generated using the JQuery Flip plugin. Within the "verso" property, there is a select menu with the ID #ddlBookletType, which triggers another JQuery plugin that creates dropdown menus. The current HTML stru ...

Ways to change the border color of Bootstrap cards

While working on my webpage, I utilized bootstrap cards to maintain a clean and organized layout. By default, bootstrap cards are white in color. Unlike the navbar, where you can easily set color options like navbar-dark, changing the color of the cards re ...

Switch images when hovering

I currently have two dropdown menus called NEW and SHOP. When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class. Whil ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...