1

I want to change the opacity of my fixed navbar background when user scrolling the page. Initially navbar background should be transparent and when scrolling down it background needs to be change to white. Like this example https://codepen.io/michaeldoyle/pen/Bhsif

I have found various examples for this scenario using jquery. But I need to achieve this using vuejs.

$(window).scroll(function() {
  if ($(document).scrollTop() > 200) {
    $('nav').addClass('transparent');
  } else {
    $('nav').removeClass('transparent');
  }
}); 

I tried above code inside my vue page. I put it inside mounted(). But it doesn't work. I need to done this using vue. Not like above jquery.

<nav class="navbar navbar-inverse">
      <ul class="nav menu">
<li>
  <router-link to="/about" @click.native="closeNavBarFromChild">About</router-link>
</li>
<li class="hidden-lg hidden-md">
  <router-link to="/product" @click.native="closeNavBarFromChild">Product</router-link>
</li>
</ul>
    </nav>

This is how my navbar component looks like.

nav.navbar{
   -webkit-transition: all 0.4s ease;
   transition: all 0.8s ease;
}

.navbar-inverse {
    background-color: rgba(255,255,255,0);
}

nav.navbar.transparent {
  background-color:rgba(0,0,0,1);
}

this is the css part that i used.

3
  • But it doesn't work - in what way? errors in the console? what doesn't work about it? Commented Oct 4, 2020 at 8:12
  • nothing appears in console. I just use jsfiddle.net/m7yww8oa/157 this simple example for testing. nothing happens. I put that jquery code inside mounted(). Is that right? Commented Oct 4, 2020 at 8:41
  • Oh, I thought you were using vuejs Commented Oct 4, 2020 at 10:53

1 Answer 1

1

Set your listener in created lifecycle hook:

export default {
  created () {
    window.addEventListener('scroll', this.onScroll);
  },
  destroyed () {
    window.removeEventListener('scroll', this.onScroll);
  },
  methods: {
    onScroll (event) {
      // add/remove class
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.