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.

2

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.