javascriptdivi

Return not working in IF statement in Javascript with DIVI


Basically i'm trying to make an animation start when in view of the user so far i had a success but now that i'm trying to make things simplier my if is not catching the return of my function, return console.log(); works fine but when i try to return a value the if just ignores it. returning always false as a result.

NOTE: I'm a junior dev using DIVI as a framework

Global JS!

<script>
  //Getting element and window parameters
  var $window = $(window);
  function check_if_in_view(el) { //Da finire
    var $element = $(el);
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);
    $(el).each(function() {
      var element_height = $(this).outerHeight();
      var element_top_position = $(this).offset().top;
      var element_bottom_position = (element_top_position + element_height);
      console.log($(this).attr('id'));
      //check to see if this current container is within viewport
      if ((element_bottom_position >= window_top_position) &&
          (element_top_position <= window_bottom_position)) {
        console.log('true');
        return true;
      } else {
        console.log('false');
        return false;
      }
    });
  };
</script>

Page-specific JS!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
  $('.fadeInLeft').css({'right' : '700px', 'opacity' : '0'});
  $('.fadeInRight').css({'left' : '700px', 'opacity' : '0'});

  function animateFadeLeft(el) {
    $(el).each(function() {
      if(check_if_in_view($(this))) {
        console.log('sono dentro')
        $(this).animate({right: '0px', opacity : '1'}, 1200);
      }
    });
  }

  $(window).on('DOMContentLoaded load resize scroll', function(){
    animateFadeLeft('.fadeInLeft');
    animateFadeLeft('.fadeInRight'); //To add
  });
</script>

I'm really sorry about the formatting of it but DIVI really sucks when formatting things since you have like a 2 inch code bar where to write it so it always messes up

(using divi because of the business where i'm learning for school)

I tried a lot actually but right now my mind is kinda blank but should be something really simple that i did not notice or something much more theoryc that i don't know still Using $().each since i have different ID's but if do not use Each my console returns error not being able to read element top position. Also i would really love any advice about making it simplier or just better performance wise thanks!


Solution

  • The problem it would seem is that you're returning from an inner function you defined in the each call. Define a variable before your each call, and then set it to true or false in the function called by each. After the each call return that variable.