Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use a javascript variable within blade curly braces

I have a video player site and i have a "next" button which should stop the video , change the src directing to the next video and play it using javascript but I cant get around using a javascript loop to change the src.

Heres my blade file

@extends('layouts.app')
@section('content')
<section class="player">
  <center>
    <video id="myvideo" class="playing-video" src="{{url('songs/'.$songs[0]->filename)}}" controls autoplay onended="nextVideo()">
    </video>
    <br>
    <button id="next" style="background-color: transparent;border: none;color: white;" onclick="nextVideo()" type="button">
    <h2><i class="fas fa-chevron-right"></i>Next</h2></button>
  </center>
</section>

and heres the javascript which is not working

var i = 0;
var myVideo = document.getElementById("myvideo");

function nextVideo() {
  i++;
  myVideo.setAttribute("src", "http://localhost/Laravel/anime/public/songs/" + {{ $songs[i] -> filename }});
  myVideo.load();
  myVideo.play();
}

I know I cant use a javascript variable inside the blade curly braces directly but I am out of ideas!

like image 296
Jaidev Das Avatar asked Feb 19 '26 10:02

Jaidev Das


1 Answers

Store the Laravel collection as a data point on the button:

<button id="next" data-songs="{{json_encode($songs)}}" ... etc />

Then pull the JS object out within the nextVideo() JS method and loop on it (all JS):

function nextVideo() {
    var songs = JSON.parse( //get the data from the #next button )
    //loop using the JS songs object instead of the blade {{}}
}
like image 123
Watercayman Avatar answered Feb 21 '26 22:02

Watercayman