Логическая ошибка в карусели Boostrap с видео IFrame на Youtube

#javascript #jquery #bootstrap-4

Вопрос:

Я пытался сделать загрузочную карусель с видео, которая автоматически скользит прямо по окончании одного из видео

Я использую API IFrame YouTube и загрузочную карусель v.4.1. 3, потому что по какой-то причине в версии 5 возникли некоторые проблемы с jQuery (при первом использовании)

Теперь, когда карусель скользит, она непрерывно скользит снова и снова без конца, не позволяя воспроизводить видео. Я предполагаю, что это потому, что всякий раз, когда карусель скользит, начинает воспроизводиться видео, и всякий раз, когда начинается воспроизведение видео, карусель скользит, я пытаюсь исправить это в коде, но не могу уловить это.

У меня возникли проблемы с вставкой только той части приложения, которая мне нужна, поэтому я просто вставлю все целиком, у меня болит голова из-за видеоплеера внизу

 const sleep = (delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });
}

// Ma gandesc ca astsa trateaza back slashuriile mai diferit
// [21:57, 7/29/2021] Viktorashi: eu scriu acum mai mutle mesaje una dupa alta
// [21:57, 7/29/2021] Viktorashi: casa incerc sa fac un mic programel
// [21:57, 7/29/2021] Viktorashi: cu care poti sa stergi in ceputiriile alea de mesaje de
// pe wapp cand dai copypaste ca sa fie mai usor mai rapid un pic

// let re1 = /ab c/;
const regexNoNames = /[d{2}:d{2},s[1-9]{1,2}/[1-9]{1,2}/d{4,10}]s.*?:|[d{1,2}/d{1,2},sd{1,2}:d{1,2}]s.*?:/gi;

const regexNames = /[d{2}:d{2},s[1-9]{1,2}/[1-9]{1,2}/d{4,10}]s|[d{1,2}/d{1,2},sd{1,2}:d{1,2}]s/gi;


const form = document.querySelector('#form')
const paragraph = document.querySelector('#message')
const input = form.elements.input
const copyButton = document.querySelector('#copy')
const nameOption = document.querySelector('#select')
const body = document.querySelector('body')



const carousel = $('#carousel').carousel()

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


let player1;
let player2;
let player3;

function onYouTubeIframeAPIReady() {

  player1 = new YT.Player('player1', {
    height: '390',
    width: '300',
    videoId: '7PiXpXQiRgA',
    playerVars: {
      playsinline: 1,
      controls: 0,
      loop: 1,
      enablejsapi: 1,

      playlist: `PiXpXQ7iRgA`,

    },
    events: {
      'onReady': onPlayerReady1,
      'onStateChange': onPlayerStateChange1
    }
  });
  player2 = new YT.Player('player2', {
    height: '390',
    width: '300',
    videoId: 'Nn4VnKcpwuk',
    playerVars: {
      playsinline: 1,
      controls: 0,
      loop: 1,
      enablejsapi: 1,

      playlist: 'Nn4VnKcpwuk',
    },
    events: {
      'onReady': onPlayerReady2,
      'onStateChange': onPlayerStateChange2
    }
  });
  player3 = new YT.Player('player3', {
    height: '390',
    width: '300',
    videoId: 'T_u3GBFOMyQ',
    playerVars: {
      playsinline: 1,
      controls: 0,
      loop: 1,
      enablejsapi: 1,

      playlist: `T_u3GBFOMyQ`,
    },
    events: {
      'onReady': onPlayerReady3,
      'onStateChange': onPlayerStateChange3
    }

  });

  const carouselItems = document.querySelectorAll('.carousel-item')
  for (let carouselItem of carouselItems) {
    carouselItem.children[0].classList.add('d-block');
    carouselItem.children[0].classList.add('w-100');
  }

}

// 4. The API will call this function when the video player is ready.

function onPlayerReady1(event) {
  event.target.mute()
}

async function onPlayerReady2(event) {
  event.target.mute()

  // await sleep(7000)
  // event.target.playVideo()


}

async function onPlayerReady3(event) {
  event.target.mute()
}

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.

async function onPlayerStateChange1(event) {
  while (player1.getCurrentTime() === player1.getDuration()) {
    carousel.carousel('next')
    await sleep(100)
  }
}

// if (event.target.getCurrentTime() === event.target.getDuration()) {
//     players[1].playVideo()

// }



async function onPlayerStateChange2(event) {
  while (player2.getCurrentTime() === player2.getDuration()) {
    carousel.carousel('next')
    await sleep(1000)
  }
}

async function onPlayerStateChange3(event) {
  while (player3.getCurrentTime() === player3.getDuration()) {
    carousel.carousel('next')
    await sleep(100)
  }
}


// relatedTarget: The DOM element that is being slid into place as the active item.
// slid.bs.carousel This event is fired when the carousel has completed its slide transition.
let count = 1

carousel.on('slide.bs.carousel', () => {
  // e.relatedTarget.firstChild.src = src   `amp;autoplay=1`
  if (count < 3) count  
    else count = 1


  switch (count) {
    case 1:
      player1.playVideo()

      player3.stopVideo()
      break;
    case 2:
      player2.playVideo()

      player1.stopVideo()

      break;
    case 3:
      player3.playVideo()

      player2.stopVideo()

      break;
  }
  console.log(count)

  // src = src   `amp;autoplay=1`
})

carousel.on('slid.bs.carousel', () => {
  // e.relatedTarget.firstChild.src = src   `amp;autoplay=1`


  // src = src   `amp;autoplay=1`
})

let mesaje = []

copyButton.addEventListener('click', e => {
  copyText(mesaje)
})

async function removeFormatting(input, regex) {
  if (input) {
    if (regex.test(input)) {
      document.querySelector('#error').classList.add('invisible')
      mesaje = input.replaceAll(regex, '')
      const clean = mesaje.replaceAll('n', '<br>')
      // const clean = mesaje.map(msg => (regex.test(msg) ? '' : msg))
      // let touchedInput = input.replaceAll(regex, '');
      paragraph.innerHTML = clean
      input = ''
      return mesaje
    } else {
      paragraph.value = ''
      document.querySelector('#error').innerHTML = ''
      document.querySelector('#error').classList.remove('invisible')
      document.querySelector('#error').innerHTML = `<h1>"${input}"</h1>
    <span> Doesn't contain any whatsapp timestamps, names etc..</span>`
      throw (`"${input}"
   Doesn't contain any whatsapp timestamps, names etc..`)
    }
  }

}

nameOption.addEventListener('change', async event => {
  // NU DECOMENTA ASTA CA SE BULESTE TOT PRGORAMU
  // while (
  //   document.querySelector('#error').classList[0] != 'invisible' amp;amp;
  // // !input.value
  // ) {
  //   document.querySelector('#error').classList.add('invisible')
  // }
  console.log(event)
  if (mesaje.length !== 0) {
    try {
      if (nameOption.value === 'noName') {
        await removeFormatting(input.value, regexNoNames)
        copyText(mesaje)




      } else if (nameOption.value === 'name') {
        await removeFormatting(input.value, regexNames)

        copyText(mesaje)


      }
    } catch (e) {
      console.log(e)
    }
  }
})

//res = string.replace(regexie, ``)



input.addEventListener('input', async e => {
  const input = form.elements.input
  // NU DECOMENTA ASTA CA SE BULESTE TOT PRGORAMU
  // while (
  //   document.querySelector('#error').classList[0] != 'invisible' amp;amp;
  // // !input.value
  // ) {
  //   document.querySelector('#error').classList.add('invisible')
  // }
  console.log(e)
  try {
    if (nameOption.value === 'noName') {

      await removeFormatting(input.value, regexNoNames)

    } else if (nameOption.value === 'name') {
      await removeFormatting(input.value, regexNames)
    }
    if (e.inputType === "insertFromPaste") {
      copyText(mesaje)
    }
  } catch (e) {
    console.log(e)
  }

})

form.addEventListener('submit', e => {
  e.preventDefault()
  const input = form.elements.input
  console.log(e)
  if (nameOption.value === 'noName') {
    removeFormatting(input.value, regexNoNames)
  } else if (nameOption.value === 'name') {
    removeFormatting(input.value, regexNames)
  }
})



function copyText(text) {
  let textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("Copy");
  textArea.remove();
  alert('Messages have been coppied to clipboard!')
}

// flickerBgColor()

// [8/11, 11:53] Viktorashi: bebe neataa
// [8/11, 11:53] Viktorashi: ce facii
// [8/11, 17:01] Viktorashi: nu intrbea
// [8/11, 17:09] Viktorashi: era buletinu meu ma rog

// if (input.splice(`4`) === 'names') {
// }


const changeBgColor = (color) => {
  body.style.backgroundColor = color
}
const flickerBgColor = async() => {
  while (true) {
    changeBgColor('yellow')
    await sleep(1000)
    changeBgColor('turquoise')
    await sleep(1000)
    changeBgColor('orange')
    await sleep(1000)
    changeBgColor('#df05f381')
    await sleep(1000)
  }
} 
 .invisible {
  display: none;
}

.invisible>* {
  display: none;
}

#message {
  color: green;
  border: 80%;
}

#error h1 {
  color: #ff0000;
}

#error,
#errorText {
  color: red !important;
  border: red;
}

svg {
  position: relative;
}

body {
  transition: all 1s;
}


/* 
#copyInput {
  display: none;
} */

textarea {
  width: 100%;
}


/* @media (max-width: 767px) {
        .top-content .carousel-control-prev,
        .top-content .carousel-control-next {
            display: none;
        }
        .top-content .carousel-indicators li {
            margin-left: 10px;
            margin-right: 10px;
        }
    } */

#input {
  border-radius: 3%;
}

#input:active {
  border: none;
}

.carousel-item * {
  width: 50%;
} 
 <!DOCTYPE html>
<html>




<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r 8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">

  <link rel="stylesheet" href="./style.css">


  <title>Expresii regulare sau cum le zice</title>
</head>

<body>

  <div class="content">
    <div class="card">
      <header class="card-header">
        <p class="card-header-title">
          <span class="title is-large">Paste the messages in the field below</span>
        </p>
      </header>
      <div class="card-content">


        <h3 id='message' class='is-large is-success  is-bordered box'></h3>
        <button id="copy" class="button is-rounded">
                    <span class="icon-text">
                        <span class="icon">
                            <svg style="width:24px;height:24px" viewBox="0 0 24 24">
                                <path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z" />
                            </svg>
                        </span>
                        <span>Copy Messages</span>
                    </span>
                </button>




        <p id='error' class="box"></p>

        <form action="/regex english.js" id="form">
          <div class="field">
            <label class="label is-medium" for="select">Select wether you want to leave the names in</label>
            <div class="select is-rounded">
              <select name="select" id="select">
                <option value="noName">Don't display the name</option>
                <option value="name">Leave the names in</option>
              </select>
            </div>
          </div>

          <textarea class="" name="input" id="input" rows="10" placeholder="[13:22, 8/5/2021] Viktorashi: This is a demo for my stupid app 
[13:22, 8/5/2021] Viktorashi: I hope you like [13:22, 8/5/2021] Viktorashi: How I'm typing all this 
[13:22, 8/5/2021] Viktorashi: Stupid stuff
[13:22, 8/5/2021] Viktorashi: In seperate messages
[13:23, 8/5/2021] Viktorashi: Is it annoying? Yes"></textarea>

        </form>
      </div>
    </div>

  </div>

  </div>

  <!-- <iframe width="921" height="518" src="https://www.youtube.com/embed/PiXpXQ7iRgA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> -->

  <!-- <iframe width="921" height="518" src="https://www.youtube.com/embed/Nn4VnKcpwuk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> -->

  <!-- <iframe width="921" height="518" src="https://www.youtube.com/embed/T_u3GBFOMyQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> -->

  <!-- Incepe caruseulu  -->
  <!-- <video src="https://www.youtube.com/watch?v=PiXpXQ7iRgA"></video> -->




  <div id="carousel" data-interval='0' class="carousel slide">
    <ol class="carousel-indicators">
      <li data-target="#carousel" data-slide-to="0" class="active"></li>
      <li data-target="#carousel" data-slide-to="1"></li>
      <li data-target="#carousel" data-slide-to="2"></li>
    </ol>
    <div class="carousel-inner">
      <div class="carousel-item active">
        <div id="player1"></div>
      </div>
      <div class="carousel-item">
        <div id="player2"></div>
      </div>
      <div class="carousel-item">
        <div id="player3"></div>

      </div>
    </div>
    <a class="carousel-control-prev" href="#carousel" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carousel" role="button" data-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>


  <!-- altu  -->

  <!-- <button id='refresh' onclick='window.location.reload(false)'>Click here, or refresh the page to write something again/button> -->
  <div class="container is-bordered is-large">
    <p>Heyy what's good, or should I say, WhatsApp?? Haha very funny ok now use my app bye. Ok so basically, you know when you copyaste a bunch of whatsapp messages they're all annoyingly formatted with name and date and time in them, well you can just paste
      them in the line below, and using a regural expression carefully created, designed, tested and uhh marketing adjectives, by yours truly, all your wanted messages will be displayed in the paragrph below, ready for you to copypaste to yo relatives,
      so what are you waiting for? U͓̕sé͓͉͔̫̲̫̳ ̦̯̙̜̱̻̪m̲̱͠y̙̤ ̖̫̬̕a͜p̢̫͇͚̝̰̦̤p͈̀ ͝a̰̺l̘͙͎ͅr̘̟̯͖̻ͅe̮͇̟a̜͇̭͠ͅd̯̺̯̻͜y̹̝͚̜̫̫͞
    </p><br>

    <h1>Turn this:</h1>
    <p>[13:22, 8/5/2021] Viktorashi: This is a demo for my stupid app <br> [13:22, 8/5/2021] Viktorashi: I hope you like <br> [13:22, 8/5/2021] Viktorashi: How I'm typing all this <br> [13:22, 8/5/2021] Viktorashi: Stupid stuff <br> [13:22, 8/5/2021] Viktorashi:
      In seperate messages <br> [13:23, 8/5/2021] Viktorashi: Is it annoying? Yes</p>
    <h1>Into this:</h1>
    <p>This is a demo for my stupid app <br> I hope you like <br> How I'm typing all this <br> Stupid stuff <br> In seperate messages <br> Is it annoying? Yes
    </p>

  </div>



  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV 2 9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3 MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

  <!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> -->

  <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script> -->

  <script src='./regex english.js'></script>

</body>

</html>