When Swiper is not in viewport go to first slide

I have a page with many Swipers, they all occupy the height and width of the screen.
I want them to go back to the first swiper position when they are not visible on the screen.

I got this function to detect the height of viewport

$.fn.isInViewport = function () {
 var elementTop = $(this).offset().top;
 var elementBottom = elementTop + $(this).outerHeight();
 var viewportTop = $(window).scrollTop();
 var viewportBottom = viewportTop + $(window).height();
 return elementBottom > viewportTop && elementTop < viewportBottom;
};

And then this function for detect scroll
The ‘test’ class is just adding for testing.

$(window).scroll(function () {
   $('.swiper-container').each(function(i, el){ 
    if ($(this).isInViewport()) {
     $(this).addClass('test');
     console.log('content block is in viewport.', $(this));
   } else{               
    $(this).removeClass('test');
    console.log('content block is not in viewport.', $(this));
    var mySwiper = $(this).attr('id');
    var mySwiper = document.querySelector('#'+mySwiper).swiper;
    console.log(mySwiper);
    mySwiper.slideTo(0);
  }
 })
});

The ID is the swipers name.
I can detect when the Swipers are on screen or not, but I can’t get them back to first place.
I know the problem is in this line
var mySwiper = document.querySelector('#'+mySwiper).swiper;
That is because the mySwiper variable always takes the value (ID) of the first Swiper, so it is the only one that works and returns to the first slide when I scroll and exit the screen.
But i can’t figured how to make it work.
Thanks.

Nevermind, i find a solution.
When the Swiper is in viewport add a class inviewport. Then on scroll, c heck if the div has the class inviewport , if positive goto first slide.

This is the second function

$(window).scroll(function () {
 $('.swiper-container').each(function(i, el){
  if ($(this).isInViewport()) {
   $(this).addClass('inviewport');
  } else{
   if ($(this).hasClass('inviewport')){
    var mySwiper = $(this).attr('id');
    var mySwiper = document.querySelector('#'+mySwiper).swiper;
    mySwiper.slideTo(0);
    $(this).removeClass('inviewport');
   }
  }
 })
});

The complete code

$.fn.isInViewport = function () {
 var elementTop = $(this).offset().top;
 var elementBottom = elementTop + $(this).outerHeight();
 var viewportTop = $(window).scrollTop();
 var viewportBottom = viewportTop + $(window).height();
 return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).scroll(function () {
     $('.swiper-container').each(function(i, el){
      if ($(this).isInViewport()) {
       $(this).addClass('inviewport');
      } else{
       if ($(this).hasClass('inviewport')){
        var mySwiper = $(this).attr('id');
        var mySwiper = document.querySelector('#'+mySwiper).swiper;
        mySwiper.slideTo(0);
        $(this).removeClass('inviewport');
       }
      }
     })
});