Checking whether an element is visible or not on the page

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 one is hidden.

I made the function in jQuery using .is(':visible') , but it did not work, because I wanted to see if the element was being displayed on the screen, 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');
   }
});
    
asked by anonymous 05.01.2018 / 18:41

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, putting 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 pick up whether or not he is on the screen by scrolling.

Result: link

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

    
05.01.2018 / 19:36