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

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...

Tips for loading all background images simultaneously

I just created my first website page with a few background images that crossfade. However, I am experiencing an issue where the next background image takes some time to load during the crossfading effect if the page is not cached on the user's comput ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

What steps do I need to take to develop a syntax similar to Vue.js using only plain JavaScript?

<div id=""> <span>{{msg}}</span> </div> Assume that {{msg}} is a variable in JavaScript. Now, I aim to locate the parent tag of {{msg}} and replace its content with a new value using innerHTML, where {{msg}} serves as an identi ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

Incorporating the elements of an array into an unordered list for a formatted list display

I have a list here <ul> <li> This is</li> <li> a very nice</li> <li> list</li> </ul> This is a very nice list and this code to insert the array elements into the list var names =["tom", " ...

Buttons in HTML function properly on desktop but are ineffective on mobile devices

My website is almost complete, but I am facing some challenges with the mobile version. All buttons that use JavaScript are not functioning properly, whereas buttons with simple links work perfectly fine. This issue doesn't occur on Chrome when using ...

Set the android camera resolution to a lower setting automatically when a user attempts to upload a file from their browser

In my current application, I have implemented a feature that allows users to upload files. When the user clicks on the input field, they are presented with options to either select a video from their gallery or open the camera to record a new video and u ...

Incorporating personalized CSS into Drupal 7 for concealing the notice

Utilizing my custom block to showcase a flash game on the main page of my Drupal 7 setup, I encountered an irksome message: <div id="first-time"><p>No front page content has been created yet.</p> <div class="item-list"><ul>&l ...

Looking for the function to activate when the enter key is pressed

I have a search box which is a text type and has a click button that initiates the Find() function. How can I enable searching by pressing Enter inside the textbox? ...

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

Create a custom CSS style to replace the default jQuery hide() function

HTML <div class="adm-input" <?php if(!empty($admin_fee) || $admin_fee != "") echo "style='display:block'"; ?> id="fees-input"> <label>Admission Fees(<i class="fa fa-inr"></i>)</label> <div class="in ...

Utilize Bootstrap in an Angular template to effortlessly expand one element while collapsing all others

I'm facing an issue with a table in my component. Each row has a button that, when clicked, should expand to show some calculated data specific to that row. However, the problem is that when one button is expanded, it keeps other buttons expanded as w ...

Count the occurrences of different fields in a document based on a specified condition

Seeking a way to extract specific values and calculate the frequency of those values in a collection based on a certain key's ID. Consider this example of a single document from a Game Logs collection: { "_id": "5af88940b73b2936dcb6dfdb", "da ...

Stop md-select dropdown from opening when clicked in specific scenario

I currently have a situation where I want to prevent the md-select from opening under a specific condition and instead display a warning dialog. One way I can achieve this is by disabling the md-select using the following code: ng-disabled="controller.un ...

toggle between utilizing the page object API and the primary Nightwatch API

Currently, I am incorporating the page object model alongside nightwatch for my testing procedures. Encountering challenges while trying to interact with an element led me to execute some jquery. However, the 'execute' command is not featured in ...

The absence of a type annotation for `T` has been noted

Attempting to create code with a simple JavaScript function: filterArray(user: any, items: Array<Object>) { items = items.filter(item => {return true;}); return items; } Encountering the following error: Error message: Missing type anno ...

Can you provide instructions on utilizing the async .update() function for DataTables within MDBootstrap?

I am just starting to explore MDBootstrap and I'm currently focused on grasping how to utilize the DataTables. While I've browsed through the examples on their website regarding Async table updates, I've found it a bit challenging to adapt i ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...