Generating keyframes spontaneously, unable to remove commas

Initially, I acknowledge that this code may not be the most elegant. I have simplified it to show only the essentials.

My objective is to dynamically create a @-webkit-keyframe based on input, generate a class, and then apply that class so an object can cycle through selected colors.

The issue I'm encountering is that when constructing my keyframe rule and inserting elements from my array, they end up separated by commas. I've attempted using .replace(", ", " ") without success.

Is there a method to remove those commas in order for my rule to be correctly formatted? The keyframe functions properly if only one box is checked, but fails to produce the desired outcome when multiple boxes are checked. The problematic array causing issues is keyframeRules found on line 51 of the pen.

Additionally, this is only my second post ever, so apologies if I'm not adhering to the correct etiquette with the code snippets.

http://codepen.io/JoeyCinAZ/pen/shgca

function keyframeValues() {
//declare an array to store values of checked boxes in
var colors = [];

//get values of checked boxes
var boxPicker = document.getElementsByName('test');
for(i = 0; i < boxPicker.length; i++) {
    if(boxPicker[i].checked) {
        var color = (boxPicker[i].alt);
        colors.push(color);                    
    }
}

//declare variable to store length of the array, and a list of colors to be used
var howMany = colors.length;
var useColors = colors;

var fraction;
    if(howMany === 0) {
        alert('error');
    }
    else if(howMany === 1){
        fraction = (1/howMany) * 100;
    }
    else{
        fraction = (1/howMany).toFixed(2) * 100;
    }

//give each line an incremental percentage
var count = 1;
//declare an array that will store the percentages  for each line in the keyframe
var myPercent = [];
    for( i = 0; i < howMany; i++) {
        var increment = count * fraction;
        var inc = increment;
        myPercent.push(increment);
        count++;
    }
    var usePercentages = myPercent;     
createKeyframe(howMany, usePercentages, useColors )
}
//create a function that takes in parameters to create the keyFrame
function createKeyframe(lineNums, usePercentages, strokecolor) {
    //create a unique name for the keyframe
    var keyframeName = "keyname" + lineNums;

    //create a keyframe that can be used to style the bed appropriately
    var line1 = "@-webkit-keyframes " + keyframeName + "{ \n0% { stroke: white; } \n";

    //create an array to store individual rules for the keyframe
    var keyframeRules = [];

    //use a loop to create additional lines to the keyframe
    for(i = 0; i < lineNums; i++) {
        var rule = usePercentages[i] + '% { background-color: ' + strokecolor[i] + '; } \n';
        keyframeRules.push(rule);
    }



//create keyframe
    var useKeyframe = line1 + keyframeRules + '}' +  '\n.' + keyframeName + '{\n-webkit-animation: ' + keyframeName + ' 2000ms ease infinite;\n}';
    var classToAssign = '.' + keyframeName + '{\n-webkit-animation: ' + keyframeName + ' 2000ms ease infinite;\n}';
    //create class variable for inline assignment
    var dot = classToAssign.indexOf('.');
    var keyframeLength = keyframeName.length + 1;
    var inlineClass = classToAssign.slice(1, keyframeLength);

    //create style element to insert newly created keyframe into
    var newStyle = document.createElement('style');
    newStyle.id = "myStyle";
    //attach new style element to <head> tag
    document.head.appendChild(newStyle);
    var ss = document.getElementById('myStyle');
    ss.textContent = useKeyframe;

    //assign newly created class to element
    var useBed = document.getElementById('bed');
    useBed.setAttribute('class', inlineClass);
}

Answer №1

The inclusion of commas stems from the type conversion rules in JavaScript. Consider this:

> ['a','b','c']+''
'a,b,c'

When dealing with an Array like keyframeRules, ensure to use keyframeRules.join('\n'):

var useKeyframe = line1 + keyframeRules.join('\n') + '}' +  '\n.' + keyframeName + '{\n-webkit-animation: ' + keyframeName + ' 2000ms ease infinite;\n}';

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

Error with the Knockout framework's inability to bind to the model

I seem to be encountering an issue with binding Knockout to a model in my code. Despite the code firing and returning a JSON object, the table appears empty. Any advice or suggestions would be greatly appreciated. HTML <table style="border: double"& ...

React component encountering unexpected prop value

In my project, I have a Modal component and a Form component. The Modal is a functional component, while the Form is a class component responsible for handling form submissions. The Modal component passes all of its props to the Form component. Within Mod ...

Jump to a specific section on a different page when the links are already equipped with anchors for smooth scrolling

My website has a menu on the home page that scrolls to specific id positions: <li><a href="#event-section">El evento</a></li> <li><a href="#asistentes-section">Asistentes</a></li> <li><a href="#cont ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

Enhance the keyup search function to accept the input value as well

I currently have a keyup search function that works when a user types directly into the field. Here is the code snippet: if(this.$search_ele.length){ this.has_search = true; this.searchFn = this.buildSearchFn(opts.fields); this.bindEv ...

ASP.Net does not support the compilation of AngularJS

Good Evening! I've been struggling with implementing an ASP.NET API, as my angular code seems to be not compiling correctly. I recently set up a new empty web project, installed angular and jquery through NUGET, and now I'm facing issues while ...

I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file. <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { ...

How to modify a specific property of an array object in JavaScript

I have an array of objects that looks like this: [ { number: 1, name: "A" }, { number: 2, name: "e", }, { number: 3, name: "EE", } ] I am looking for a way to insert an object into the array at a specific position and ...

When trying to assign the result of res.send() to another variable in NodeJS Express, it does

My current Express version is 3.4.4 and I encountered an issue when trying to implement the following code: var cb = res.send; cb(result); This resulted in an error message: ...\node_modules\express\lib\response.js:84 var HEAD ...

Looking for some guidance on JavaScript and CSS

I have a JavaScript function that animates clouds moving across the screen. I am trying to restrict the area they cover to only occupy the top 300px of the screen. I attempted to add "height:300px; top:0px;" to the DIV style, but it didn't produce th ...

The persistent space between the navbar and the index page remains despite the suggested fixes provided

There appears to be a discrepancy between the navigation bar and the rest of the page. Despite my efforts to adjust margins, I haven't been able to resolve it. The system is prompting me for more details before posting this question, but I'm unsu ...

Switch up the display and concealment of div elements with the power of

Looking for a solution to alternate between "cheese" and "wine" divs output to the page with PHP? Take a look at this code: <div class="cheese"></div> <div class="wine"></div> <div class="cheese"></div> <div class="c ...

Transforming table headers in Rmarkdown ioslides

I am experimenting with creating a custom table format for tables generated using the ioslides_presentation output type in Rmarkdown with Rstudio Version 0.98.1028. However, I'm facing difficulty in modifying the styling of the table headers. Below i ...

Looking to boost the height of ngSelect options?

Need help with adjusting the dropdown height for the ng-select form image. Currently, it is only displaying 5 items and I would like it to show 8-10 items. Below is the code I am using: <form [formGroup]="addReportForm" class="form-hori ...

Are background styles complete without incorporating quotations?

Let's say I want to include a background image, my code might look like this: background: url(/images/button_bg.png) repeat-x scroll left bottom #146BAE However, when I check the code in Firebug, it shows: background: url("/images/button_bg.png") r ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

Different approaches for expanding object.prototype while utilizing jQuery

Once upon a time, I made the mistake of trying to extend Object.prototype and ended up encountering errors in my jQuery file. After doing some research, I found out that extending Object.prototype is frowned upon in the JavaScript community due to potentia ...

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...