skip to Main Content

I have a button element with a .hover property and I need the hover animation to also happen as soon as the page is mounted. How can I attribute a class to a button on the mounted function and then disattribute it?

I was thinking of using a setTimeout but it’s not working properly. I’m basing my code off of this codePen: https://codepen.io/lucasfads/pen/QWwjGjv

<a href="#" class="button" id="specialButton">
  <span class="icon"></span>
  <span class="text">Hakuna Matata</span>
</a>
mounted() {
  document.getElementById("specialButton").classList.add("expanded");

  setTimeout(() => {
    document.getElementById("specialButton").classList.remove("expanded");
  }, 3000);
}
.button {
  background-color: #099;
  color: white;
  text-decoration: none;
  border-radius: 60px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  overflow:hidden;
  width: auto;
  max-width: 32px;
  transition: max-width 0.5s;
}

.button:hover,
.button .expanded {
  max-width: 300px;
}

.icon {
  font-family: "Font Awesome 5 Free";
  font-size: 16px;
  margin-right: 15px;
  padding: 0px 8px;
  display: flex;
  align-items: center;
}

.text {
  white-space: nowrap;
  padding-right: 15px;
}

2

Answers


  1. It should be .button.expanded not .button .expanded

    Other than that, see a comment from Jaromanda X, I agree that using direct DOM manipulations in Vue is a bad indicator.

    Another thought – it’ll probably be more efficient to have that class by default, and then remove it later. Otherwise you mount, add class, remove class – 3 DOM operations. Instead you can just mount, remove class – 2 DOM operations.

    Login or Signup to reply.
  2. Please take a look at following snippet (Vue way, no need to get element ):

    new Vue({
      el: '#demo',
      data() {
        return {
          initBtn: true
        }
      },
      mounted() {
       setTimeout(() => this.initBtn = false, 3000);
      }
    })
    .button {
      background-color: #099;
      color: white;
      text-decoration: none;
      border-radius: 60px;
      height: 32px;
      display: inline-flex;
      align-items: center;
      overflow:hidden;
      width: auto;
      max-width: 32px;
      transition: max-width 0.5s;
    }
    
    .button:hover,
    .button.expanded {
      max-width: 300px;
    }
    
    .icon {
      font-family: "Font Awesome 5 Free";
      font-size: 16px;
      margin-right: 15px;
      padding: 0px 8px;
      display: flex;
      align-items: center;
    }
    
    .text {
      white-space: nowrap;
      padding-right: 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <a href="#" class="button" :class="initBtn && 'expanded'">
        <span class="icon"></span>
        <span class="text">Hakuna Matata</span>
      </a>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search