Home > database >  Jquery doesn't get element by class [duplicate]
Jquery doesn't get element by class [duplicate]

Time:09-16

Hope you're doing great :)

I'm trying to make a rolling animation and I've this code in my local jquery.js file:

$(() => { 

  /*  Components */

  $(".navbar_section").load("../components/navbar.html");
  $(".title_section").load("../components/title.html");
  $(".welcome_section").load("../components/welcome.html");
  $(".trust_section").load("../components/trust.html");
  $(".menu_section").load("../components/menu.html");
  $(".parallax_section").load("../components/parallax.html");
  $(".location_section").load("../components/location.html");
  AOS.init();

  /*  Animations */

  $(function () {
    var pizzaLeft = $(".pizza-menu-left");
    $(window).on("scroll", () => {
      var scroll = $(window).scrollTop();
      if (scroll >= 1500) {
        pizzaLeft.removeClass("roll-out-left");
        return pizzaLeft.addClass("roll-in-left");
      } else {
        pizzaLeft.removeClass("roll-in-left");
        return pizzaLeft.addClass("roll-out-left");
      }
    });
  });
});

The problem is this, .pizza-menu-left doesn't get selected, but all the classes above do. I've tried, live(), on(), but nothing seems to work. I know it's all about the time of the DOM objects and attributes being created, certainly, the function above is running before the class attribute is set. Still, I don't know how to get around this.

CodePudding user response:

Assuming .pizza-menu-left are elements that are loaded dynamically, they will not be available when the onl oad function runs, so you'll need to define that variable inside the event handler.

$(function () {
    $(window).on("scroll", () => {
      var pizzaLeft = $(".pizza-menu-left");
      var scroll = $(window).scrollTop();
      if (scroll >= 1500) {
        pizzaLeft.removeClass("roll-out-left");
        return pizzaLeft.addClass("roll-in-left");
      } else {
        pizzaLeft.removeClass("roll-in-left");
        return pizzaLeft.addClass("roll-out-left");
      }
    });
  });
  • Related