Home > Software engineering >  jquery scroll() executing multiple times
jquery scroll() executing multiple times

Time:09-05

I'm using jQuery to add a button next to all A>SPAN tags found on a page. The page itself grows as the user scrolls down, which is why I'm using the Scroll function - I need to continually add the button to the new page sections.

The below code continually adds buttons to the sections that already have buttons on them. I'm trying to only show one button next to each found tag combination. I've tried every combination I can think of. I'm hoping someone has an easy solution I can try.

Thank you.

$(window).scroll(function () {
  if (!$("a span button").length) {
    $("a span").after(
      ' <button type="button" >BUTTON</button>'
    );
  }
});

CodePudding user response:

jQuery's .after() inserts a sibling element, not a descendant. For example, if you had

<a>
  <span>Text</span>
</a>

the result of your code would be

<a>
  <span>Text</span>
  <button>BUTTON</button>
</a>

This doesn't match your selector "a span button" because the <button> is not a descendant of the <span>.

I would instead add some property or class to the <span> to identify that it has been button-ised, then you can omit those elements in your selections

$(window).scroll(() => {
  $("a span:not(.buttonised)").each((_, span) => {
    $(span)
      .addClass("buttonised")
      .after(
        $("<button>", {
          class: "btn btn-secondary btn-sm",
          text: "BUTTON",
          type: "button",
        })
      );
  });
});
  • Related