Modal’s button doesn’t work!

Asked

Viewed 51 times

-1

I own a modal that warns about Policies and Terms of Use. Basically it will close if clicked on any area outside of it and the close button, but I tried to implement (unsuccessfully) that it was closed when the button I have read and agree to the terms. The button just doesn’t work! I have no idea when what is the error (of logic, can only), because I believe that of syntax is not.

Follow the representation and the code:

.modal-container {
    font-family: tahoma;
    width: 100vw;
    height: 100vh;
    /*width: 500px;*/
    /*height: 574px;*/
    border-radius: 6px;
    background: rgba(0, 0, 0, .5);
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 2000;
    display: none; /*pq nao ocultou?*/
    justify-content: center;
    align-items: center;
}

.modal-container.mostrar {
    display: flex;
}


.modal {
    background: white;
    width: 36%;
    min-width: 300px;
    padding: 5px;
    border: 10px solid #2a8096;
    border-radius: 10px;
    box-shadow: 0 0 0 10px white;
    position: relative;
    
}

@keyframes {
    from {
        opacity: 0;
        transform: translate3d(0, -60px, 0);
    }
    to {
        opacity: 1;
        transform: translate3d(0, 0, 0);
    }
}

.mostrar .modal {
    animation: modal .3s;
}

.fechar {
    position: absolute;
    font-size: 1.2em;
    top: -30px;
    right: -30px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 4px solid white;
    background: #988b7a;
    color: white;
    cursor: pointer;
    box-shadow: 0 4px 4px 0 rgba(0, 0, 0, .3);
}
h5 {
    margin-left: 15px;
    margin-top: 30px;
    margin-bottom: 20px;
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 500;
}

li {
    font-size: 1.08em;
    padding: 0px 10px;
}

#li-destacado {
    color: #2a8096;
}

.btn-block {
    display: block;
    width: 100%;
}

.btn-primary {
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
}

.btn {
    padding: 6px 12px;
    margin-bottom: 0px;
    font-size: 14px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    touch-action: manipulation;
    cursor: pointer;
    border: 1px solid transparent;
    border-radius: 4px;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Políticas e termos de uso</title>
    <link rel="stylesheet" type="text/css" href="_css/politicas-termos.css"/>
</head>

<body>
    <p class="logo">LOGO</p>
    <div id="modal-promocao" class="modal-container">
        <div class="modal">
            <button class="fechar">x</button>
            <h5 class="subtitulo" style="font-size: 22pt;">Regras para receber um livro</h5><hr>
            <ol>
                <li>Somente após se cadastrar no site você poderá receber um livro.</li><br/>
                <li>Só é possível solicitar um livro por vez.</li><br/>
                <li>Após escolher um livro, você deve indicar 2 novos leitores que ainda não estejam cadastrados na Livronautas.</li><br/>
                <li id="li-destacado">O Livro é <b>grátis. O custo do envio fica por sua conta</b>, para isso você precisará colaborar apenas com o valor cobrado pelos Correios, em média <b>R$ 10,00</b>. O prazo para postagem do livro é de 48h úteis após a confirmação do pagamento</li><br/>
                <li>Após receber o livro e terminar a leitura, você deve postar no site da Livronautas a sua avaliação e comentário sobre o livro que leu. Somente assim você estará liberado para fazer um novo pedido de doação</li>
            </ol>
                <button id="aceito" class="btn btn-primary btn-block">Li e concordo com os termos</button>
        </div>
    </div>
    
    <script>
        
        function iniciaModal(modalID){
            //nao usar essa primeira condição neste modal em específico.
            if(localStorage.fehaModal !== modalID){
                const modal = document.getElementById(modalID);
                if(modal){
                    modal.classList.add('mostrar');
                    modal.addEventListener('click', (e) => {
                        if(e.target.id == modalID || e.target.className == 'fechar'){
                            modal.classList.remove('mostrar');
                            localStorage.fehaModal = modalID;
                        }
                    });
                }
            }
            
        }
        
        const logo = document.querySelector('.logo');
        logo.addEventListener('click', () => iniciaModal('modal-promocao'));
        
        //Esse botão não funciona!?
        const btnAceito = document.querySelector('.btn');
        btnAceito.addEventListener('click', () => iniciaModal('modal-promocao'));
        
        document.addEventListener('scroll', () =>{
            if(window.pageXOffset > 800){
                iniciaModal('modal-promocao')
            }
        })
        
    </script>
</body>
</html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

3 answers

2


You are just checking the click outside the modal area and the close button.

Include another condition in if checking whether the id of the element clicked is equal to "accepted":

if(e.target.id == modalID || e.target.id == "aceito" || e.target.className == 'fechar'){
                          ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

Tip

Do not use localStorage.fehaModal = modalID;. Instead use:

localStorage.setItem("fehaModal", modalID);
  • Interestingly, I advanced my studies and saw about key => value. I ended up finding problems later in this code, exactly for lack of attention. For Ex.: the name would be closeModal instead of "fehaModal".

0

Try the following :

document.getElementById("aceito").addEventListener("click", function() {
    document.getElementById("modal-promocao").style.display = "none";
});

0

Good morning.

This answer is being given in a context where it is not known if there are more buttons on the screen, but this situation will be considered.

A possible way to solve your problem would be to specify the button click accepted, because you know which button it is (there is a id) and knows what its purpose is, to close the modal and perhaps perform some other function.

Instead of being run the routine iniciaModal (which, by the way, will already be started) you could already be running the closing of the modal and another routine that is necessary for your case.

Your function is being executed but the if(e.target.id == modalID || e.target.className == 'fechar') is always returning false

Note: I do not know if it was really the goal, I believe not, but beware of the use of addEventListener, the way it’s being is being added more than handle to the click in modal.

Browser other questions tagged

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