Using JavaScript variables in CSS: a beginner's guide

My website features a typewriter effect, but I want the animation to match the length of the words exactly. I attempted using JavaScript variables in CSS, but unfortunately, it's not functioning properly. Could someone please advise me on how to remedy this issue?

const text = document.getElementById("second-text");

const textLoad = () => {
    setTimeout(() => {
          text.textContent = "Freelancer";
          let Steps = 10;
          0); setTimeout(() => {
            text.textContent = "Editor";
            let Steps = 6;
            4000); setTimeout(() => {
              text.textContent = "Coder";
              let Steps = 5;
              8000);
          }

          textLoad(); setInterval(textLoad, 12000);
>body {
  background: black;
  margin: 0;
  padding: 0;
  font-family: "Poppins";
  display: grid;
  place-items: center;
  height: 100vh;
  width: 100%;
}

.container {
  width: 300px;
  overflow: hidden;
}

.container .text {
  position: relative;
  color: white;
  font-size: 30px;
  font-weight: 600;
  align-items: start;
}

.container .first-text {
  color: white;
}

.container .second-text::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: black;
  border-left: 2px solid #4070f4;
  animation: animate 4s steps(var(--Steps)) infinite;
}

@keyframes animate {
  0% {
    left: 0%;
  }
  40%,
  60% {
    left: calc(100% + 4px);
  }
  100% {
    left: 0%;
  }
}
<div class="container">
  <span class="text first-text">Hi! I am </span>
  <span class="text second-text" id="second-text">Freelancer</span>
</div>

Answer №1

Opting for the CSS variables method shows good reasoning

In my opinion, the JavaScript code you wrote might not properly communicate with the CSS. Here's a suggestion.

CSS

You can continue using var(--steps), just like you have been

JavaScript

document.documentElement.style.setProperty('--steps', 8000);

Answer №2

If you want to change the background color of an element dynamically, you can use inline styles in HTML to set the value of a CSS custom property. This custom property can then be referenced in your CSS code. For example:

<div style="--color: red"> ... </div>
.someSelector {
   background: var(--color); /* red */
}

Here is a demo showcasing how you can cycle through a set of background colors by clicking on the element. The JavaScript function updates the inline style to set the CSS --color property:

const colors = ['red', 'blue', 'green'];
const demo = document.getElementById('demo');

let colorIndex = 0;
function nextColor() {
  colorIndex = (colorIndex + 1) % colors.length;
  demo.style = `--color: ${colors[colorIndex]}`;
}

demo.addEventListener('click', nextColor);
#demo {
  background: var(--color, skyblue);
  padding: 2rem;
}
<div id="demo">click me</div>

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

Getting an out-of-range exception (System.ArgumentOutOfRangeException) in C# Razor pages while attempting an AJAX call

I have a razor page model that contains a get-method. public IActionResult OnGetDuration([FromBody]int id) { Subject subject = _service.GetSubjectById(id); int duration = subject.LessonsPerWeek; return new JsonResult('a&apo ...

Controlled Checkbox Component in React

I'm really struggling with this. While I can easily work with select drop downs and text fields, I just can't seem to get checkboxes to function properly in a controlled manner. I want them to 'toggle' and respond to events in a parent ...

The Controller of Conversations

In the HTML code, there is a dialog element with an identification of divMyDialog1. This dialog is connected to a JavaScript class called MyDialog1. Each dialog has its own unique id and associated class name. MyDialog1 = function(divStr){ this.divStr ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

Receiving a Javascript Promise from a $.ajax request

Trying to convert a $.ajax() statement into an es6 Promise and return it as an es6 promise. The goal is to have an application layer with Create, Update, Delete calls to the Microsoft Dynamics Web API that return an es6 Promise for reuse across multiple pa ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

Effective URL structure with nested ui-view in AngularJS

It is common knowledge that Angular functions as a SPA (Single Page Application). I am seeking the most effective approach to display a main left-side menu selector page, where clicking on any menu item will load the content in the right-side view div. Th ...

Is there a way to use JavaScript to switch the entire div on and off

I have a function called done that I want to use to toggle the visibility of my "temp" division. tasks.innerHTML += `<div id="temp"> <span id="taskname"> ${input.value} </span> <button class="d ...

Unable to trigger ActionFunction with Remix and MUI slider

I am trying to implement a MUI slider in order to update a database by using Remix ActionFunction. The issue I am facing is that when the MUI slider is moved, it reloads the default function instead of calling the ActionFunction. How can I make it trigger ...

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

Having trouble with your website's container not wrapping properly?

I've run into an issue where my container is not wrapping a border around the other elements, only around the header. I checked with validators for both CSS and HTML but there are no errors being shown. Does anyone have an idea what might be causing t ...

After the recent update to version 4.2.0 of @material-ui/core, unexpected react hook errors have been

Currently, I am working on an electron application that utilizes react and material-ui. Recently, I made the decision to update material-ui to version 4.2.0. As a result of this update, two lines were added to my dependencies in the package.json. "@materi ...

Element Not Adjusting to Content Size

I am encountering an issue with my div. I have floated an image to the right and placed my text beside it. My aim is to create a div with a linear gradient, however, the div ends up filling the entire page. How can I make my div adjust to fit only its con ...

Creating a CSS layout that eliminates the need for a vertical scroll bar

Currently, I am experimenting with creating an HTML CSS Layout using the div tag. You can view the code here Currently, the layout displays a vertical bar that I would like to eliminate. Ideally, I only want it to display if the content is lengthy. ...

Why does the image return an Undefined Value when clicked? Is there a solution to this issue?

Every time I click on an image, I encounter the error message "undefined." Can someone please shed some light on why this is happening and provide guidance on how to successfully retrieve and pass the value to the onclick function in this particular scen ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

Enhance the functionality of your website by implementing a zoom feature

I am looking to dynamically change the CSS of a div using jQuery when it is clicked. The challenge I am facing is that there are multiple divs with the same class and I am unable to modify their classes as they are created dynamically using PHP. <div ...

Tips for saving the ajax response to the browser cache using jquery

I am currently working on storing the ajax response in the browser cache. I have successfully managed to store it for URLs like (example.com), but now I am facing a challenge with storing data for URLs like (example.com?xyz=abc%20efg&mno=hjk). Here is ...