0

I have a jquery script that generates items dynamically on the scroll. By default, the overlay style for these items is set as visibility: hidden I decided to change the overlay style on the fly a checkbox, and make them visible:

 $(' #switch').click(function() {
        if ($(this).prop("checked") == true) {          


            $('.footer-inner').css({ visibility: 'visible' });

        } else if ($(this).prop("checked") == false) {

            $('.footer-inner').css('visibility', 'hidden');

        }
    });

The code trigger well for all the items already created on the page. But if I scroll down, the news items don't have the overlay is not visible.

hello B
  • 826
  • 3
  • 16
  • 39
  • https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling and https://stackoverflow.com/questions/37240594/jquery-scroll-function-fire-once-when-element-becomes-visible – caramba Feb 11 '20 at 20:08
  • So when you add the new items you would need to trigger the code. You would be better off with just a CSS solution. – epascarello Feb 11 '20 at 20:34

1 Answers1

1

I would just toggle a CSS class on a parent and use a style to show and hide the element. No need to worry about calling the function when the page updates. It just gets applied.

$('#switch').on('change', function() {
  $(".wrapper").toggleClass("show-footer", this.checked)
}).change();

var i = 4;
window.setInterval(function() {
  i++
  $(".wrapper").append(`<div>${i}</div><div class="footer-inner">${i}X</div>`)
}, 2000)
.wrapper .footer-inner {
  display: none;
}

.wrapper.show-footer .footer-inner {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="switch"><label>Toggle</label>

<div class="wrapper">
  <div>1</div>
  <div class="footer-inner">1X</div>
  <div>2</div>
  <div class="footer-inner">2X</div>
  <div>3</div>
  <div class="footer-inner">3X</div>
  <div>4</div>
  <div class="footer-inner">4X</div>

In your way with toggling the visibility, you would need to trigger the function after the page updates. So you would need to call $('#switch').click() when you make the update.

And depending on the layout, it would be possible to do it in pure CSS using checkbox state.

var i = 4;
window.setInterval(function() {
  i++
  $(".wrapper").append(`<div>${i}</div><div class="footer-inner">${i}X</div>`)
}, 2000)
.wrapper .footer-inner {
  display: none;
}

#switch:checked + label + .wrapper .footer-inner {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="switch"><label>Toggle</label>
<div class="wrapper">
  <div>1</div>
  <div class="footer-inner">1X</div>
  <div>2</div>
  <div class="footer-inner">2X</div>
  <div>3</div>
  <div class="footer-inner">3X</div>
  <div>4</div>
  <div class="footer-inner">4X</div>
epascarello
  • 185,306
  • 18
  • 175
  • 214