I’m trying to create a carousel so I can click through each element in csv file:
In a routes/index.js file I’m reading a csv file with film data in an array, and then loading this into the index.ejs file when its opened:
//get request - open index.ejs page
router.get(['/', '/index', '/discover', '/home'], function (req, res) {
//read film data into array for frontend
const films = [];
fs.createReadStream('film_data.csv')
.pipe(csvParser())
.on('data', (row) => {
films.push(row);
})
.on('end', () => {
res.render('index', { title: 'Express', session: { email:req.cookies.sessionEmail }, films: films });
})
});
In the index.ejs file I am trying to create a carousel so I click next or previous and show the next film title in the array:
<!-- Film carousel -->
<div class="carousel" id="film-carousel" data='<%- films %>'>
<button id="prev-btn">Previous</button>
<div id="current-film">
<!-- films displayed here from scripts/index.js -->
</div>
<button id="next-btn">Next</button>
</div>
<!-- END film carousel -->
The functionality for this is handled in the scripts/index.js file, however I don’t know how to put the array from the .ejs file to the .js file so I can implement this, does anyone know how to do this?
This is my scripts/index.js file:
window.onload = function () {
const currentFilmElement = document.getElementById('current-film');
const prevButton = document.getElementById('prev-btn');
const nextButton = document.getElementById('next-btn');
var films = document.getElementById('film-carousel').getAttribute('data');
var currentIndex = 0;
// Initial update
updateFilm();
// Function to update the displayed film
function updateFilm() {
currentFilmElement.innerHTML = `<strong>Title:</strong> ${films[currentIndex].primaryTitle} <br><p></p>`;
}
// Event listener for the previous button
prevButton.addEventListener('click', function () {
currentIndex = (currentIndex - 1);
if(currentIndex < 0) {
currentIndex = 0;
}
updateFilm();
});
// Event listener for the next button
nextButton.addEventListener('click', function () {
currentIndex = (currentIndex + 1);
updateFilm();
});
};
Currently I am trying to pass it as a data attribute which i am accessing in the scipts/index.js file, but when I try to use the array here I get errors, and rather than seeing film data it is in the format [object object], [object object] etc.
Can anyone advise?