Checking whether an item is visible or not on the page

Asked

Viewed 1,831 times

2

I have the following buttons:

First button:

<button id="modal-btn" class="button btn-cart btn-verde-claro"> <span>Comprar</span> </button>

Second button:

<div class="btn-comprar-fixed-mobile" id="btn-comprar-fixed-mobile" style="display: none">
    <button class="button btn-cart btn-verde-claro"><span>Comprar</span></button>
</div>

I wanted that when the first button appeared, the second did not appear and vice versa. When the second appears on the screen, the first was hidden.

I did the function in jQuery using the .is(':visible'), but it did not work, because I wanted to see if the element was being displayed on the screen, if not with display: none or display: block.

Function code:

$j(window).scroll(function() { 
   console.log('fazendo');  
   if($j('#modal-btn').is(':visible')){
       console.log('if');
       $j('#btn-comprar-fixed-mobile').css('display','none');
   } else{
       console.log('else');
       $j('#btn-comprar-fixed-mobile').css('display','block');
   }
});

1 answer

1


You can check if it is on the screen by checking the scroll.

As the buttons will disappear and appear, I will use the div to set when it should appear, you will do the same on your page by placing the Divs where the buttons are.

<div class="area1">
  <button id="btn1">Comprar</button>
</div>
<div class="area2">
    <button id="btn2">Comprar</button>
</div>

I created this css code so that the page can have a scroll:

body{
  background-color:#000;
}
.area1{
  background-color:#a00;
  height: 1000px;
}
.area2{
  background-color:#005;
  height: 1000px;
}

And the following code:

$(function(){
  var area1 = $('.area1').offset().top - $(window).height();
  var area2 = $('.area2').offset().top - $(window).height();

  $(window).scroll(function() {
    if ($(window).scrollTop() > area1) {
      $('#btn1').css('display','block');
      $('#btn2').css('display','none');
    }
    if ($(window).scrollTop() > area2) {
        $('#btn2').css('display','block');
      $('#btn1').css('display','none');
    }    
  });
});

So he can catch whether or not he is on the screen through the scroll.

Upshot: https://jsfiddle.net/pjqxrgwu/

Credits: How to know which div is shown on the screen with javascript?

  • I think he meant that the first button is fixed, and when it appeared or second, the first disappeared and lives-versa... by the way, the second that is fixed rs

  • @dvd that’s right. But I managed to make it work from this code, I only changed a few things in the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.