Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change css when element/div not visible on screen

In my vue web app, I'm trying to change the CSS class of header when one of the element goes off the screen via scrolling.

I am using jquery-visible to find whether the element is visible or not as I could not found any vue way to do so.

Now I have following code in HTML to change the CSS class dynamically:

<div class="aClass" :class="{'bClass': isElemVisible()}">
   ....
   ....
</div>

And in my Vue code, I have added a method as following:

export default {
  name: 'myElem',
  methods: {
    isElemVisible () {
      console.log($('#myDiv').visible(true))
      return $('#myDiv').visible(true)
    }
  }
}

The problem with this is it does not changes the value returned by isElemVisible dynamically, it just takes the first value when loaded and not changes even after scroll and #myDiv goes out of screen, How can this be done or if there is a better/vue way to do it.

like image 856
Saurabh Avatar asked May 27 '26 18:05

Saurabh


2 Answers

I suggest you listen to the scroll event, like this: https://github.com/vuejs/Discussion/issues/324

like image 112
Kevin Hutchinson Avatar answered May 30 '26 08:05

Kevin Hutchinson


The problem is that isElemVisible() is not being executed. The method has been defined and it is executed the first time that Vue is determining if bClass should be enabled, but subsequently, particularly when scrolling, it is never executed again.

Instead of a simple method that is only executed once, I'd recommend using a boolean data property that you update upon scrolling with the value returned by jquery-visible.

I have put together this CodePen to demonstrate what I mean, but in short:

<div id="myDiv" class="aClass" :class="{'bClass': isElemVisible}">
</div>

And instead of a method use a data property and a scroll event listener:

data() {
  return {
    isElemVisible: true
  }
},

created() {
  window.addEventListener('scroll', event => {
    this.isElemVisible = $('#myDiv').visible(true)
  })
}
like image 38
Rommel Santor Avatar answered May 30 '26 07:05

Rommel Santor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!