Skip to content

Commit

Permalink
Incluindo formulário do rodapé do site (#38)
Browse files Browse the repository at this point in the history
* Adicionando formulário de contato no rodapé

- Proposta de HTML a ser aplicada
- Primeiros estilos ao formulário

* Removendo placeholder quando input ou textarea está em foco

* Esconder formulário em dispositivos com resolução <= 768px

* Habilitar/Desabilitar botão de submit no formulário de contato

- Quando todos atributos estiverem preenchidos botão de submit deve ser habilitado para envio do contato

* Adicionando lógica para envio de e-mail

- Foi utilizado uma solução utilizando o Google App Scrips para envio do email,
baseado nesse tutorial: https://github.com/dwyl/learn-to-send-email-via-google-script-html-no-server

* Habilitando honeypot no formulário

* Removendo javascripts do HTML

* Alterando helper para asset ao invés de js

* Movendo javascript para diretórios js

* Alterando cor para variável

* Adicionando extensão ao arquivo javascript home

* Corrigindo um pequendo de digitação

* Movendo estilos para breakpoint do desktop

* Movendo mixin

* Removendo chamada do google sheet

* Alterando formulário para envio de e-mail
  • Loading branch information
Gabriel Silva Pereira authored Jun 18, 2018
1 parent 3f1e7c3 commit fb0bfb6
Show file tree
Hide file tree
Showing 5 changed files with 266 additions and 22 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ o servidor onde o site será instalado.
export TRAVIS_PULL_REQUEST=false

Se você adicionar uma chave pública SSH neste arquivo, o deploy não irá precisar
de senha. Essa chave pode ser encontrada em `~/.ssh/id_rs.pub`. Se não existir,
de senha. Essa chave pode ser encontrada em `~/.ssh/id_rsa.pub`. Se não existir,
será necessário criá-la com o comando
`ssh-keygen -t rsa -b 4096 -C "[email protected]"`

Expand Down
75 changes: 73 additions & 2 deletions _assets/css/footer.scss
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,66 @@
@include media-breakpoint-up(md) {
.footer {
font-size: 1.25rem;
padding: 6rem 0;

.container {
text-align: left;

.contact-us {
#thankyou_message {
display: none;
p {
margin-top: 1.5rem;
}
}

#honeypot {
display: none;
}

label {
color: $umber;
display: block;
font-weight: bold;
text-transform: uppercase;
margin-bottom: 0em;
}

input[type="email"], textarea {
width: 100%;
margin-bottom: 0.5em;
border: 2px solid $umber;
}

input[type="submit"] {
display: block;
border: 2px solid $white;
padding-left: 1.5em;
padding-right: 1.5em;
background-color: transparent;
color:$white;
}

input[type="submit"] {
float: right;
cursor: pointer;
}

input[type="submit"]:disabled {
opacity:0.5;
cursor: not-allowed;
}
}
}

.contact-info {
padding-left: 3em;
}

address {
margin-top: 1.5rem
}

.top-button {
.top-button, .email-contact {
display: none;
}

Expand All @@ -71,3 +124,21 @@
}
}
}

@mixin placeholder {
::-webkit-input-placeholder {@content}
:-moz-placeholder {@content}
::-moz-placeholder {@content}
:-ms-input-placeholder {@content}
*:focus::-webkit-input-placeholder { color:transparent; }
*:focus:-moz-placeholder { color:transparent; } /* FF 4-18 */
*:focus::-moz-placeholder { color:transparent; } /* FF 19+ */
*:focus:-ms-input-placeholder { color:transparent; }
}

@include placeholder {
font-family: $font-amatic;
color: gray;
font-weight:100;
padding-left: 0.5em;
}
130 changes: 130 additions & 0 deletions _assets/js/form-submission-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
$(document).ready(function() {
validateInputsRequired();
$('.required').on('keyup', validateInputsRequired);
});

function validateInputsRequired() {
var inputsWithValues = 0;
var inputsRequired = $('.required');

inputsRequired.each(function() {
if ($(this).val()) {
inputsWithValues += 1;
}
});

if (inputsWithValues == inputsRequired.length) {
$('input[type=submit]').prop('disabled', false);
} else {
$('input[type=submit]').prop('disabled', true);
}
}

function validEmail(email) { // see:
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}

function validateHuman(honeypot) {
if (honeypot) { //if hidden form filled up
console.log("Robot Detected!");
return true;
} else {
console.log("Welcome Human!");
}
}

// get all data in form and return object
function getFormData() {
var form = document.getElementById("gform");
var elements = form.elements; // all form elements
var fields = Object.keys(elements).filter(function(k) {
// the filtering logic is simple, only keep fields that are not the honeypot
return (elements[k].name !== "honeypot");
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var data = {};
fields.forEach(function(k){
data[k] = elements[k].value;
var str = ""; // declare empty string outside of loop to allow
// it to be appended to for each item in the loop
if(elements[k].type === "checkbox"){ // special case for Edge's html collection
str = str + elements[k].checked + ", "; // take the string and append
// the current checked value to
// the end of it, along with
// a comma and a space
data[k] = str.slice(0, -2); // remove the last comma and space
// from the string to make the output
// prettier in the spreadsheet
}else if(elements[k].length){
for(var i = 0; i < elements[k].length; i++){
if(elements[k].item(i).checked){
str = str + elements[k].item(i).value + ", "; // same as above
data[k] = str.slice(0, -2);
}
}
}
});

// add form-specific values into the data
data.formDataNameOrder = JSON.stringify(fields);
data.formGoogleSendEmail = form.dataset.email || ""; // no email by default

console.log(data);
return data;
}

function handleFormSubmit(event) { // handles form submit withtout any jquery
event.preventDefault(); // we are submitting via xhr below
var data = getFormData(); // get the values submitted in the form

if (validateHuman(data.honeypot)) { //if form is filled, form will not be submitted
return false;
}

if( data.email && !validEmail(data.email) ) { // if email is not valid show error
var invalidEmail = document.getElementById("email-invalid");
if (invalidEmail) {
invalidEmail.style.display = "block";
return false;
}
} else {
var url = event.target.action; //
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
console.log( xhr.status, xhr.statusText )
console.log(xhr.responseText);
document.getElementById("gform").style.display = "none"; // hide form
var thankYouMessage = document.getElementById("thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k])
}).join('&')
xhr.send(encoded);
}
}

function loaded() {
console.log("Contact form submission handler loaded successfully.");
// bind to the submit event of our form
var form = document.getElementById("gform");
form.addEventListener("submit", handleFormSubmit, false);
};

document.addEventListener("DOMContentLoaded", loaded, false);
2 changes: 1 addition & 1 deletion _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ contato:
telefone: (11) 3032-6032
endereco_1: Rua Aspicuelta, 678, Vila Madalena
endereco_2: 05433-011 - São Paulo - SP
# Configurações da ferramenta
formulario_google_app_script: https://script.google.com/macros/s/AKfycbzsH6VKhze2mrBehy5YvporLJ24IbjQUSzhykhsgalUroMiBpI/exec
timezone: UTC
collections:
posts:
Expand Down
79 changes: 61 additions & 18 deletions _includes/footer.html
Original file line number Diff line number Diff line change
@@ -1,23 +1,66 @@
<footer class="footer">
<div class="container">
<h2>Fale com a gente</h2>
<a class="email-contact" href="mailto:{{ site.contato.email }}">{{ site.contato.email }}</a>
<address>
<p class="phone">{{ site.contato.telefone }}</p>
<p class="address-1">{{ site.contato.endereco_1 }}</p>
<p class="address-2">{{ site.contato.endereco_2 }}</p>
</address>
<div class="social-icons">
<a href="https://www.facebook.com/associacaovagalume/" target="_blank">
<img src="/assets/img/facebook.png" alt="Vaga Lume no Facebook">
</a>
<a href="https://www.instagram.com/_vaga_lume_/" target="_blank">
<img src="/assets/img/instagram.png" alt="Vaga Lume no Instagram">
</a>
<div class="row">
<div class="contact-us col-md-4 d-none d-md-block">
<form id="gform" method="POST" action="{{ site.contato.formulario_google_app_script }}">
<label class="sr-only">Keep this field blank</label>
<input id="honeypot" type="text" name="honeypot" value="" />
<div class="form-group">
<label for="email">Email</label>
<input id="email"
type="email"
name="email"
required
placeholder="Digite seu email"
oninvalid="this.setCustomValidity('Por favor preencha com um e-mail válido')"
oninput="setCustomValidity('')"
class="required" />
</div>
<div class="form-group">
<label for="message">Mensagem</label>
<textarea id="message"
required
name="message"
rows="4"
placeholder="Deixe sua mensagem para nós"
oninvalid="this.setCustomValidity('Você deve preencher com alguma mensagem')"
oninput="setCustomValidity('')"
class="required"></textarea>
</div>
<div class="form-group">
<input type="submit" disabled=true value="Enviar" />
</div>
</form>

<div id="thankyou_message">
<p>
Obrigado! Sua mensagem foi enviada com sucesso!
</p>
</div>
</div>

<div class="contact-info col-md-4">
<a class="email-contact" href="mailto:{{ site.contato.email }}">{{ site.contato.email }}</a>
<address>
<p class="phone">{{ site.contato.telefone }}</p>
<p class="address-1">{{ site.contato.endereco_1 }}</p>
<p class="address-2">{{ site.contato.endereco_2 }}</p>
</address>
<div class="social-icons">
<a href="https://www.facebook.com/associacaovagalume/" target="_blank">
<img src="/assets/img/facebook.png" alt="Vaga Lume no Facebook">
</a>
<a href="https://www.instagram.com/_vaga_lume_/" target="_blank">
<img src="/assets/img/instagram.png" alt="Vaga Lume no Instagram">
</a>
</div>
</div>
</div>
<a class="top-button" href="#top">Voltar ao Topo &#9650;</a>
</div>
</footer>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Expand All @@ -27,11 +70,11 @@ <h2>Fale com a gente</h2>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
crossorigin="anonymous"></script>
{% asset jquery.slides.min.js %}
{% asset home.js %}
{% asset expedicao.js %}

</body>
{% asset jquery.slides.min %}
{% asset home.js %}
{% asset expedicao %}
{% asset form-submission-handler %}

</body>
</html>

0 comments on commit fb0bfb6

Please sign in to comment.