View JSON data in carousel (scroll infinite Javascript)

Asked

Viewed 48 times

1

I made an infinite scroll in JS, IE, every time the page reaches the end is made a GET request for a page of the site itself that returns films of a genre in JSON but, when it scrolls again the new films should be placed in other carousels. Below are the codes I made (codeigniter 3): Data returned by "API":

[
{
"slug": "2018ej982je",
"img": "roxo.png",
"nome": "8",
"descricao": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"duracao": "02:11",
"classificacao": "1",
"ano": "2000",
"genero": "Ação"
},
{
"slug": "2018ej982je",
"img": "roxo.png",
"nome": "5",
"descricao": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"duracao": "02:11",
"classificacao": "1",
"ano": "2000",
"genero": "Ação"
},

This is a chunk of code that displays a carousel correctly, but this one is only for understanding

if(isset($filmes_familia)){ ?>
    <div class="container-fluid mt-5" style="margin-bottom: 50px !important;">
        <div class="row">
            <div class="col-md-12">
                <div class="ne_busness_main_slider_wrapper">
                    <div class="ne_recent_heading_main_wrapper">
                        <h2 style="color: white; font-weight: bold; margin-left: 15px;">Filmes para toda família</h2>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container-fluid filme ">
        <div class="owl-carousel owl-theme home-slider nav-outer show-nav-hover nav-image-center filmes_familia" data-owl-options="{
            'loop': false,
            'autoHeight': true,
            'dots': false,
            'nav': false,
            'margin': 15,
            'autoplay': false,
            'responsive': {
                '1080': {
                    'items': 5  
                },
                '640': {
                    'items': 3  
                },
                '480': {
                    'items': 2  
                }
            }
        }
        ">
        
        <?php foreach($filmes_familia as $filme){ ?>
            <div class="list-item">
                <div class="film-list">
                    <a href="<?php echo base_url('perfil/watch?code='.$filme->filme_slug); ?>">
                        <figure class="zoom">
                            <img src="<?php echo base_url('assets/imagens/filmes/mini/'.$filme->filme_imagem_principal); ?>" alt="<?php echo $filme->filme_nome; ?>" style="width: 100%;">
                        </figure>
                    </a>
                    <div class="actions">
                        <div class="title">
                            <h5 class="text-white"><?php echo $filme->filme_nome; ?></h5>
                        </div>
                        <div class="actions-list">
                            <div class="row">
                                <ul>
                                    <div class="col play"><li><a href="<?php echo base_url('perfil/watch?code='.$filme->filme_slug); ?>" data-title="Assistir" class="title-tip"><i class="icon fas fa-play-circle"></i></a></li></div>
                                    <div class="col plus"><li><a href="<?php echo base_url('perfil/mylist/'.($this->Core_model->get_by_id('minha_lista', array('minha_lista_perfil_id' => $perfil->perfil_id, 'minha_lista_slug' => $filme->filme_slug)) ? 'del' : 'add').'/'.$filme->filme_slug); ?>" data-title="Adicionar a minha lista" class="title-tip"><i class="icon fas fa-plus"></i></a></li></div>
                                    <div class="col thumbs-up"><li><a href="<?php echo base_url('perfil/home/like_add/'.$filme->filme_slug); ?>" data-title="Gostei deste filme" class="title-tip"><i class="icon fas fa-thumbs-up"></i></a></li></div>
                                    <div class="col thumbs-down"><li><a href="<?php echo base_url('perfil/home/deslike_add/'.$filme->filme_slug); ?>" data-title="Não gostei deste filme" class="title-tip"><i class="icon fas fa-thumbs-down"></i></a></li></div>
                                    <div class="col info-circle"><li><a href="<?php echo base_url('perfil/detalhes?code='.$filme->filme_slug); ?>" data-title="Mais Detalhes" class="title-tip"><i class="icon fas fa-info-circle"></i></a></li></div>
                                </ul>
                            </div>
                        </div>
                        <div class="descr">
                            <p>
                                <?php 
                                    $str=strlen($filme->filme_descricao);
                                    if ($str > 90) {
                                        echo substr($filme->filme_descricao,0,91).'...';
                                    }else{
                                        echo $filme->filme_descricao;
                                    }
                                ?>
                            </p>
                        </div>
                        <div class="rule">
                            <p> <?php echo $filme->filme_duracao; ?> &nbsp;&nbsp; <?php echo $filme->filme_ano; ?> &nbsp;&nbsp; 
                            <?php switch ($filme->filme_classificacao) { 
                                case 1: echo '<span style="background: green; padding: 2px 8px; border-radius: 5px;">L</span>';break;
                                case 10: echo '<span style="background: Lightskyblue; padding:  0 5px; color: #fff;  border-radius: 5px;">10</span>'; break;
                                case 12: echo '<span style="background: yellow; color: black; padding:  0 5px; color: #fff;  border-radius: 5px;">12</span>'; break;
                                case 14: echo '<span style="background: orange; padding: 0 5px; color: #fff; border-radius: 5px;">14</span>'; break;
                                case 16: echo '<span style="background: red; padding: 0 5px; color: #fff;  border-radius: 5px;">16</span>'; break;
                                case 18: echo '<span style="background: black; padding: 0 5px; color: #fff;  border-radius: 5px; border: 1px solid #fff;">18</span>'; break;
                                } ?>
                                 Classificação Conteúdo</p>
                        </div>
                    </div>
                </div>
            </div>
        <?php } ?>
        <script>
            jQuery(document).ready(function($) {
                var carouselList = $(".filmes_familia");
                checkList();
                carouselList.on('translated.owl.carousel', function(event) {
                    checkList();
                });
                function checkList(){
                    var totalList = $('.filmes_familia .owl-stage .owl-item.active').length;
                    //console.log(totalList);
                    $('.filmes_familia .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem');
                    $('.filmes_familia .owl-stage .owl-item.active').each(function(index){
                        if (index === 0) {
                            // this is the first one
                            $(this).addClass('firstActiveItem');
                        }
                        if(totalList >= 5){
                            if (index === totalList - 1 && totalList>1) {
                                // this is the last one
                                $(this).addClass('lastActiveItem');
                            }
                        }
                    });
                }
            });
        </script>
            
        </div>
    </div>

<?php
} ?>

The javascript code that I made it works takes the next movies of other genres, but the problem is to display these other movies in new carousels:

<!-- GENEROS  INIFITE SCROLLING -->
<div class='container-fluid divContainers'></div>

<div class="loader">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
</div>

<script>
    const postsContainer = document.querySelector('.divContainers')
    const loaderContainer = document.querySelector('.loader')
    let page = 1
    

    const getPosts = async () => {
        const response = await fetch(`https://sitedaapi/API/generos?genero=${page}`)
        return response.json()
    }

    const addCarrossel = () => {
        postsContainer.innerHTML = `
        <div class="container-fluid mt-5" style="margin-bottom: 50px !important;">
            <div class="row">
                <div class="col-md-12">
                    <div class="ne_busness_main_slider_wrapper">
                        <div class="ne_recent_heading_main_wrapper">
                            <h2 style="color: white; font-weight: bold; margin-left: 15px;">Filmes x</h2>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container-fluid filme ">
            <div class="owl-carousel owl-theme home-slider nav-outer show-nav-hover nav-image-center filme_${page}" data-owl-options="{
                'loop': false,
                'autoHeight': true,
                'dots': false,
                'nav': false,
                'margin': 15,
                'autoplay': false,
                'responsive': {
                    '1080': {
                        'items': 5  
                    },
                    '640': {
                        'items': 3  
                    },
                    '480': {
                        'items': 2  
                    }
                }
            }
            ">
            
            </div>
        </div>`
    }
    
    const addPostsIntoDOM = async () => {
        const posts = await getPosts()
        const postsTemplate = posts.map(({ slug, img, nome, descricao, duracao, classificacao, ano, genero }) => `
            <div class="list-item">
                <div class="film-list">
                    <a href="<?php echo base_url('perfil/watch?code='); ?>${slug}">
                        <figure class="zoom">
                            <img src="<?php echo base_url('assets/imagens/filmes/mini/'); ?>${img}" alt="${nome}" style="width: 100%;">
                        </figure>
                    </a>
                    <div class="actions">
                        <div class="title">
                            <h5 class="text-white">${nome}</h5>
                            </div>
                        <div class="actions-list">
                            <div class="row">
                                <ul>
                                    <div class="col play"><li><a href="<?php echo base_url('perfil/watch?code='); ?>${slug}" data-title="Assistir" class="title-tip"><i class="icon fas fa-play-circle"></i></a></li></div>
                                    
                                    <div class="col thumbs-up"><li><a href="<?php echo base_url('perfil/home/like_add/'); ?>${slug}" data-title="Gostei deste filme" class="title-tip"><i class="icon fas fa-thumbs-up"></i></a></li></div>
                                    <div class="col thumbs-down"><li><a href="<?php echo base_url('perfil/home/deslike_add/'); ?>${slug}" data-title="Não gostei deste filme" class="title-tip"><i class="icon fas fa-thumbs-down"></i></a></li></div>
                                    <div class="col info-circle"><li><a href="<?php echo base_url('perfil/detalhes?code='); ?>${slug}" data-title="Mais Detalhes" class="title-tip"><i class="icon fas fa-info-circle"></i></a></li></div>
                                </ul>
                            </div>
                        </div>
                        <div class="descr">
                            <p>
                                descrição temporária
                            </p>
                        </div>
                        <div class="rule">
                        <p> 
                            <span style="background: green; padding: 2px 8px; border-radius: 5px;">L</span>
                            Classificação Conteúdo
                        </p>
                        </div>
                    </div>
                </div>
            </div>
        `).join('')
        document.querySelector('.filme_'+`${page}`).innerHTML += postsTemplate
    }

    addCarrossel()
    addPostsIntoDOM()

    const getNextPosts = () => {
        page++
        addPostsIntoDOM()
    }

    const removeLoader = () => {
        setTimeout(() => {
            loaderContainer.classList.remove('show')
            getNextPosts()
        }, 1000)
    }

    const showLoader = () => {
        loaderContainer.classList.add('show')
        removeLoader()
    }

    window.addEventListener('scroll', () =>{
        const { clientHeight, scrollHeight, scrollTop } = document.documentElement
        const isPageBottomAlmostReached = scrollTop + clientHeight >= scrollHeight - 10
        
        if(isPageBottomAlmostReached){
            showLoader()
        }
    })
</script>

inserir a descrição da imagem aqui

follows a print to understand the problem (movies for the whole family are correct but x films would be the films of the new carousels.

  • Obs: the movies for the whole family is not in the js code it is fixed on the page, load along with the normal page loading.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.