Ways to apply CSS styles dynamically within a v-for loop

Despite searching through the VUE official website and various other sources, I have not been able to find a satisfactory solution. I am reaching out for assistance, thank you in advance.


        <div class="tag-item" :ref="`tagItem_${index}`">
          <el-tooltip effect="dark" :content="tag.name" placement="top">
            <el-link :underline="false" class="title" @click="getPostByTag(tag)">
              <el-image :src="tag.img" style="height: 32px; z-index: 99; width: 32px" lazy />
              <span class="content" :id="`content_${index}`" :class="judgeScroll(index)">{{ tag.name }}</span>
            </el-link>
          </el-tooltip>
        </div>
    

        const tagItem_0 = ref()

        const judgeScroll = (index) => {
          nextTick(() => {
            let contentWidth = document.getElementById(`content_${index}`).clientWidth
            if (+contentWidth > +tagItem_0.value[0].clientWidth) {
              document.getElementById(`content_${index}`).classList.add('scroll')
              return 'scroll'
            }
          })
        }
    

        .tag-list {
          margin: 10px;
          min-height: 32px;
          min-width: 10%;

          .tag-item {
            width: 100%;
            padding: 1%;
            max-width: 100%;

            .title {
              color: #262626;
              display: block;
              line-height: 20px;
              font-size: 13px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-wrap: normal;
              max-width: inherit;
              align-items: center;

              .content {
                white-space: nowrap;
                overflow: hidden;
              }

              .scroll {
                animation: scrollText 10s linear infinite;
                @keyframes scrollText {
                  0% {
                    transform: translateX(30%);
                  }
                  100% {
                    transform: translateX(-100%);
                  }
                }
              }
            }
          }
        }
    

In my concept, when the text within the span exceeds the container's width, I want to apply CSS styling to make it scroll horizontally. If the 'scroll' style is applied successfully, it signifies success.

If the 'scroll' style is successfully applied, it should function like this scroll example.

I intend to add the 'scroll' style to all <span> elements wider than their parent node. However, despite console logs showing correct values, the desired 'scroll' style is not returning as expected until the classList.add statement.

I currently have two primary questions: 1. The necessity of including nextTick,tagItem.value[0] to prevent null value. 2. Why the 'scroll' style is not returning upon execution.

Furthermore, when using the above setup as a component and multiple instances appear on the same page, the style gets added to all components simultaneously. Is there a workaround for this scenario?

Thank you for taking the time to read this. Any feedback or suggestions are greatly appreciated.

Answer №1

1. When the judgeScroll function is executed during the 'beforeCreate' lifecycle for the first time, the DOM has not been created yet, resulting in tagItem_0.value[0] being null. 2. Keep in mind that there is no return value in judgeScroll; your return is within a callback of nextTick. 3. Vue does not recommend using the document Object; if you do use it, consider optimizing your code accordingly. 4. Have you considered using the style 'overflow: auto'?

Supplement: Try deleting the judgeScroll function and adjusting the style as follows: .content {white-space: nowrap; overflow: auto;display: inline-block;width: calc(100% - 32px );} Additionally, if possible, showcase your code on CodePen so I can test it out.

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

Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure: <Col md="6"> <div className="hero-section"> <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}> <div className="front"> <div className="hero-section-content"> ...

Using String interpolation in Vue.js to bind a computed attribute

I am working with a set of computed data that each returns a specific URL - computed:{ facebookUrl(){return "facebook.com"}, twitterUrl(){return "twitter.com"} } Within the template, I have a v-for loop and each item has a 'name' attribute (nam ...

Sleek carousel design with optimal spacing between images

Solving the Issue Utilizing Ken Wheeler's Slick plugin has allowed me to create a carousel on my website. However, I've encountered an issue where the images inside the <a> tag aren't evenly spaced and are even overlapping in some ins ...

Starting the animation only when the slide is visible

Struggling to add animations dynamically as a HTML/CSS developer who avoids JS but uses jQuery occasionally? Sound familiar? Well, I have. Recently, I managed to create a CSS-3 animation for the images in a Bootstrap carousel. Check out the code below: ...

What could be causing the misalignment of these two divs?

I'm struggling to horizontally align these two divs using percentages for width. Even with padding and margin set to 0, they refuse to line up properly (the second one ends up below the first). This is the code I have been using: <div style="widt ...

What is the best way to continuously run a series of functions in a loop to create a vertical news ticker effect?

I'm in the process of creating a vertical latest news ticker, and although I'm new to javascript, I'm eager to learn and build it myself. So far, I've come up with this, but I want the news cycle to restart once it reaches the end. ...

"Troubleshooting: PrimeVue DataTable Not Displaying Proper

Attempting to utilize PrimeVue and implement the DataTable Component, but it is not appearing. It seems to be an issue related to $slots error? The Button component is rendering and functioning as expected. Table.vue <template> <div> ...

What are some solutions for troubleshooting setInterval issues?

I have a h1 element with a v-for loop that displays items from my array in the following format: <h1 v-for="(record, index) of filteredRecords" :key="index" :record="record" :class="get ...

Rendering a Vue component: displaying raw HTML entities without escaping them

Is there a way in Vue 2 to prevent the escape of HTML entities and have them rendered as normal text? When dealing with a tag, I know I can nest another createElement, but that's not the case here. Vue.component('my-component', { render ...

What sets apart the <img> and <Image> layout attributes in NextJS?

While working on custom checkboxes, I came across a unique situation - the only way the positioning of the checkboxes aligns properly is if the classes '.init' and '.hover' are assigned to images, and the class '.done' is disp ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

firefox is experiencing lag issues with react-spring and framer-motion

Encountering an issue with two animation libraries, react-spring and framer-motion. Attempting to create a basic animation that triggers upon the component's initial visibility (simplified version). <motion.div initial={{x: -25, opacity: 0}} anima ...

What is the best way to distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

I require assistance with the following issue: nuxt-stripejs requires a publishableKey

I am currently working on a project running locally, using VueJS and NuxtJS for the frontend and Laravel for the backend APIs. The Laravel setup has been completed successfully, but I'm encountering an error with the frontend (VueJS and NuxtJs). Even ...

How to keep Vuetify component at the top of the v-layout?

https://i.stack.imgur.com/cKdsk.png I am in the process of creating a website using vuetify and nuxt. My goal is to specify the max-width property for the expansion panel UI component (https://vuetifyjs.com/en/components/expansion-panels). Here is my curr ...

The `@import` statement fails to load styles even when the URL is perfectly accurate

I am attempting to implement CSS styles. @import url("http://mydomain.com/theme/css/reset.css") However, it seems that the styles are not being applied. When I access through the browser, I can see all the CSS rules loading. What am I doing incorrectly ...

No files found in dist/ directory when using Vue.js

Beginner's Note I must confess that I am a novice when it comes to web development. Please bear with me if this question seems silly; I appreciate your assistance in advance. Initial Setup My current node version is 16.15.1 and npm version is 9.5.0 ...

Issue with updated form input failing to submit the latest value

Below is my Vue template code: <form action="[path]/post.php" ref="vueForm" method="post"> <input type="hidden" name="hiddenfield" :value="newValue"> <input type="button" value="new value and submit" @click="changeVal(456)"> </form> ...

When working with JavaScript, the `textarea` value property will not recognize line breaks or white spaces when being read

Recently, I've been developing a browser-based notebook app. However, I encountered an issue where if I type a note like this: *hello this is my first note The app displays it as: hello this is my first note Additionally, I want elements with the ...

Eliminate the preset padding on the left and right sides of the container-fluid in Bootstrap 5

How can I remove the default padding-left and padding-right in a container-fluid using Bootstrap 5? I don't want to use "!important" in my CSS file. I have already tried disabling the default padding with Chrome dev tools but it didn't work. Any ...