Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that?

var para_values = [
  {
    content: "BRAND "
  },
  {
    content: "MISSION"
  }
];

function showVal(index) {
  var val = document.getElementsByClassName("header-para")[0];
  console.log(val);
  val.innerHTML = para_values[index].content;
}

showVal(0); // called for visibility on the screen

// function for changing the content
function textChange() {
  var index = 0;
  var intrvl = setInterval(() => {
    index = index + 1;
    if (index == para_values.length) {
      index = 0;
    }
    showVal(index)
  }, 4000)
}

textChange();
.header-para {
  height: 60px;
  background-color: rgb(51, 235, 198);
}

.text-overlay span {
  color: black;
  font-size: 56px;
}
<div class="text-overlay">
  <span>Your</span> <span class="header-para"></span><span>Understand</span>
</div>

Answer №1

My approach to styling the spans involved changing them to display inline block for better control, with added width and text alignment properties on the target span.

I also implemented a CSS class called "reveal" that triggers an animation sliding down the content, which is added dynamically in the showval function along with an event listener to remove it post-animation completion.

Moreover, I switched from using getElementsByClassName to querySelector for more efficient targeting.

To determine the widest word, I looped through the content and placed each in a temporary element to calculate the maximum width considering varying letter widths.

var para_values = [
  {
    content: "BRAND "
  },
  {
    content: "MISSION"
  }
];

const getMaxWidth = () => {
  let maxWidth = 0;
  let temp = document.createElement("span");
  temp.classList.add("ib");
  document.body.append(temp)
  para_values.forEach((e) => {
    temp.textContent = e.content;
    if(temp.offsetWidth > maxWidth){
      maxWidth = temp.offsetWidth;
    }
  });
  
  temp.remove()
  return maxWidth;
}
const spanWidth = getMaxWidth();
const wordEle = document.querySelector(".header-para");

wordEle.style.width = spanWidth + "px";

function showVal(index) {
  wordEle.innerHTML = para_values[index].content;
  wordEle.classList.add("reveal")
}

showVal(0);

function textChange() {
  
  var index = 0;
  setInterval(() => {
    
    index = index + 1;
    if (index == para_values.length) {
      index = 0;
    }
   
    showVal(index)
  }, 4000)
}

textChange();

wordEle.addEventListener("animationend", (event) => { wordEle.classList.remove("reveal")});
.header-para {
  height: 60px;
  background-color: rgb(51, 235, 198);
  text-align:center;
}

.ib,
.text-overlay span {
  color: black;
  font-size: 56px;
  display:inline-block;
}

.reveal {
    animation: slide-down 1s;
}

@keyframes slide-down {
  from {
    transform: translateY(-50px);
    opacity: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0px);
    animation: linear;
  }
}
<div class="text-overlay">
  <span>Your</span> <span class="header-para"></span><span>Understand</span>
</div>

Answer №2

If you want to style different <span> elements, you can utilize CSS selectors along with

document.querySelector('#my-span')
.

let targetSpan = document.querySelector('span');

setTimeout(() => {
  targetSpan.textContent = 'baz';
}, 3000 );
span {
  display: inline-block;
  width: 150px;
}
<p>Here is <span>hi</span> to the end.

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

What could be the reason behind ejs not allowing if else statements when the variable is undefined?

I am attempting to replicate a rather simple example from this question here <div <% if (page_name === 'overview') { %> class="menu__menu-overviewPage menu" <% } %> class="menu"> However, when I try it on a ...

Develop universal style classifications for JSS within material-ui

Currently, I am utilizing the JSS implementation of material-ui to style my classes. As I have separated my components, I find myself dealing with a significant amount of duplicated code in relation to the components' styles. For instance, I have mu ...

Utilize a while loop in JavaScript to trigger a message when a variable dips below zero

Forgive me if I seem clueless. I am a beginner in the world of Javascript and am currently experimenting with loops. At the moment, I am toying around with this particular piece of code: <!DOCTYPE html> <html> <body> <button oncl ...

Generate a custom comment page for every URL identifier

I am currently working on creating a PHP comment page that displays unique comments for each specific URL ID. However, I have encountered an issue where the comment page is shared among all URLs. I understand that I need to add the URL ID (bug ID) to the M ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Wait for Protractor until the page has completely finished loading

After navigating to https://docs.angularjs.org/tutorial, I attempted to click on '0 - Bootstrapping' under Tutorial but Protractor did not wait for the page to fully load, resulting in an Error. Error: Failed to execute 'click' on &a ...

The challenge of using CSS Flexbox to position the logo with a margin-top

While learning flexbox, I encountered a challenge. I aim to center align h1, p, and button elements, with the logo positioned at the top margin-top of 1em. Essentially, I want the h1, p, and button to be centered, while the logo is positioned at the top wi ...

Guide to deactivating the user interface in AngularJS until receiving a server response

Currently, I am in the process of developing a web application using AngularJS and Node.js (Express). During various interactions within the app, users will be required to communicate with the server. Depending on the response received, different actions ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

Determining the Area of a Polygon Based on its Slope or Angle

Is it possible to calculate the area of a polygon when it has an inclination or slope? I have both the angle/slope and the points of the polygon, and I need to determine the area. How can this be achieved? ...

Using NPM packages with vanilla JavaScript can be achieved without the need for an HTML file

Is there a way to include an NPM package in my index.js file without installing it via a package manager? I do not have an HTML file, only the index.js file which is executed with 'node index.js' command. Since I cannot use a CDN, is there any me ...

The absence of the Django CSRF token has been detected

Inside the custom.js file, there is a function defined as shown below : function contactTraxio(fullname, telephone, email) { if (typeof(fullname)==='undefined') fullname = null; if (typeof(telephone)==='undefined') telephone = ...

Implementing an Angular theme in a project using Node.js, MySQL, and Express

I'm a beginner with node, angular, and express. I've managed to create a REST API using node+express+mysql, but now I need help integrating the blur-admin theme into my existing project. Despite getting the theme to run separately with gulp, I&ap ...

Vue's watch feature will not execute if the watched property remains unchanged during a page reload

<template> <!-- The navbar has a property for gender, the color of the navbar will change depending on the gender --> <!-- pass the props gender through a form submission and event --> <div class="nav-main" :class="{f ...

Crafting a dynamic inline search form with Bootstrap

My goal is to replicate the design in this image: This is my current progress: ...

Utilize a Material UI GridList to transform images into a captivating background display

Incorporating a GridList displaying a variety of images fetched from an external source, I have successfully created an ever-changing image gallery. Now, my goal is to convert this dynamic image gallery into grayscale or transparency and utilize it as a ba ...

The Vue.js class bound to the object remains static even after the object is updated

When I have a number of buttons, generated using the v-for directive, with each button having an initial class based on a string from an object. There is an event that changes this string when a button is clicked. However, the class does not get updated a ...

Transitioning from Jquery to vanilla JavaScript or transforming Jquery code into pseudo code

Struggling with a snippet of jQuery code here. While I have a good grasp on JavaScript, my knowledge of jQuery is somewhat limited. I am seeking assistance to analyze the following code in order to translate it into plain JavaScript or pseudo code that ca ...

The font from the server is not displaying correctly in the local HTML file

After uploading the ttf font file to the server, I utilized the following CSS code: @font-face { font-family: "fontname"; src: url("http://www.mywebsite.com/Fonts/fontname.ttf"); } body { font-family: "fontname", sans-serif; } Within the loc ...

Warning message will appear before navigating away from the page if vee-validate is

Wondering how to create a simple confirmation prompt asking if the user really wants to leave a page that includes a basic HTML form. The HTML Form: <!DOCTYPE html> <html> <head></head> <body> <div id="app"> ...