Hide a DIV and show another when I press the enter key - javascript

I'm trying to do a function that when I press the enter key it disappears a div (containerMessage) and another (containerResult) one appears, what am I doing wrong? When I press the enter key the function is not even called
A Live Example
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<img src="girlfriend.png">
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome">
</form>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
</div>
<script src="NSGM.js"></script>
</body>
</html>
Javascript
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
if (document.getElementById('containerMessage').style.display == 'block') {
document.getElementById('containerMessage').style.display = 'none'
document.getElementById('containerResult').style.display = 'block'
}
}

When you press enter, the form gets submitted, so you'll have to prevent that default behaviour:
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault(); // Prevent submitting the form
validate(e);
}
});
The other issue is that you're hiding the containerMessage div which contains your containerResult, so it will never be shown. Check the snippet below, but basically you'll just have to move the containerResult div out of the containerMessage div.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
e.preventDefault();
validate(e);
}
});
function validate(e) {
let container = document.getElementById("containerMessage");
if (!container.style.display || container.style.display == "block") {
container.style.display = "none";
document.getElementById("containerResult").style.display = "block";
}
}
body {
background-color: red;
margin: 0;
}
img {
height: 50vh;
}
#bloco {
text-align: center;
margin: 0;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
}
h1 {
margin: 100px 0px 0px 0px;
font-size: 10em;
}
h2 {
margin: 0;
font-size: 3em;
}
p {
font-size: 3em;
margin: 0;
}
h1,
h2,
p {
color: white;
}
input[type="text"] {
margin: 50px 0px 0px 0px;
padding: 16px 20px;
border: none;
border-radius: 8px;
background-color: #f1f1f1;
font-size: 2em;
text-align: center;
}
input[type="text"]:focus {
background-color: #ea8079;
color: white;
outline: 0;
}
#result {
font-size: 6em;
}
#containerResult {
display: none;
}
#containerMessage {
display: block;
}
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome" />
</form>
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>

The problem is that .style.display will only return the current style if it has been previously set inline or via javascript.
Otherwise, you must use:
getComputedStyle(element, null).display
where element is previously selected in the DOM.
I removed the form from the example to remove that distraction.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
let msgDiv = document.getElementById('containerMessage');
let resDiv = document.getElementById('containerResult');
let divStyle = getComputedStyle(msgDiv, null).display;
if (divStyle == 'block') {
msgDiv.style.display = 'none';
resDiv.style.display = 'block';
}
}
#containerResult{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="bloco">
<div id="containerMessage">
Nome meu amor: <input type="text" name="name" id="digitarNome">
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
References:
https://stackoverflow.com/a/4866269/1447509

Element.style will only retrieve the styles from the attribute on the element so
document.getElementById('containerMessage').style.display == 'block'
Will always return false
From W3 schools https://www.w3schools.com/jsref/prop_html_style.asp
Note: The style property only returns the CSS declarations set in the element's inline style attribute, e.g.
. It is not possible to use this property to get information about style rules from the section in the document or external style sheets.
You can instead apply the display style as in line attribute like so
<div id="containerMassage" style="display:block"></div>

Related

how to fix onClick button for append functions?

Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated
To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>

My button (EventListener) has limited click only

I am making a modal, so i made an example to make it simple, Program goes, when i click any button, a modal will show and the page too but it will only show specific page depends on the button, in this case, uno button is for page1, dos for page2 and tres for page 3.
everything goes where i wanted until i clicked all the button, Just to show you my problem, try clicking step by step from uno to tres, then click uno again, and that's it the pages does not change at all.
can you please figure out whats wrong with my code?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 400px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
</style>
</head>
<body>
<p>Click the button to Show Modal.</p>
<div class="btns">
<button class="myBtn" id="uno">uno</button>
<button class="myBtn " id="dos">dos</button>
<button class="myBtn "id="tres">tres</button>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>
<!--JS-->
<script>
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for(let i=0; i<btn.length;i++ ){
btn[i].addEventListener('click', () => {showModal(); getId(); displayPage()});
}
function showModal(){
getModal.style.display = "block";
}
function getId(){
//console.log(event.target.id);
}
function displayPage(){
var btnId = event.target.id;
if(btnId == "uno"){
getPages[0].style.display = "block";
}else if(btnId == "dos"){
getPages[1].style.display = "block";
}else if(btnId == "tres"){
getPages[2].style.display = "block";
}
}
</script>
</body>
</html>
<html>
You are not hiding the other modal pages when you trigger the display of one of them, therefore they are all displayed at the same time once you clicked all buttons, and the one with the highest z-index (in this case automatically determined by element order in the markup) overlays all others. Set the display property to block or none depending on whether it's the current modal page or not. You can also pass the index of the modal page to the displayPage() function, so you don't need those if statements to check for the button text.
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for (let i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', () => {
showModal();
displayPage(i)
});
}
function showModal() {
getModal.style.display = "block";
}
function displayPage(pageIndex) {
var btnId = event.target.id;
getPages.forEach(function(modalPage, index) {
getPages[index].style.display = index === pageIndex ? "block" : "none";
});
}
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 400px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
<p>Click the button to Show Modal.</p>
<div class="btns">
<button class="myBtn" id="uno">uno</button>
<button class="myBtn " id="dos">dos</button>
<button class="myBtn " id="tres">tres</button>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>
The problem is with your display function. You must hide other pages when you want to show your new one. So add this function to your code.
function hideAllPages(){
getPages[0].style.display = "none";
getPages[1].style.display = "none";
getPages[2].style.display = "none"
}
}
then call it the first line of displayPage function.
function
// Hide all pages first
hideAllPages();
var btnId = event.target.
if(btnId == "uno") {
getPages[0].style.display = "block"
} else if (btnId == "dos") {
getPages[1].style.display = "block"
} else if (btnId == "tres") {
getPages[2].style.display = "block"
}
}
Also you can have some base structure for your code like:
save id of pages or (better solution) get id of the page with data-* (Exp. data-page-id="uno") in html structure and retrieve it in js with listen to click event of page button click and use getAttribute function to see which page to show
I hope it helps :)

Javascript 'type error Uncaught TypeError: Cannot set property 'backgroundColor' of undefined' but works

I have an issue with the backgroundColor property in JavaScript but my function keeps working, regardless of the error.
Can somebody explain, how this is happening?
Fiddle link
Thank you
JavaScript Code with error:
function surligne(champ, erreur)
{
if(erreur)
{
champ.style.backgroundColor = "#fba";
document.getElementById("messageErreur").style.display ="block";
}
else
{
champ.style.backgroundColor = "";
document.getElementById("messageErreur").style.display ="none";
}
Here is your error:
champ.addEventListener("blur", verifMail);
function verifMail(champ) {
change it to this:
champ.addEventListener("blur", verifMail);
function verifMail() {
Champ is already defined at the top of the file, by adding a parameter on the verifyMail function, you make it so that the function can no longer view the the champ variable at the top of the file and instead it sees the blur event.
The reason it does change color is because you call verifMail from the verifForm function, passing the champ parameter.
The loss of focus triggers the blur. It is odd that the blur comes first.that's why on focus out your function again is calling so your error happened. I've correct it with variable value hope it'll help you
If you change the alerts to console.log (or something that does not steal focus), you will see that the events fire correctly.
var modal = document.getElementById('maPopin');
var btn = document.getElementById("monBouton");
var span = document.getElementsByClassName("fermer")[0];
var champ = document.getElementById("mail");
var erreur = true;
btn.addEventListener("click", function() {
modal.style.display = "block";
});
span.addEventListener("click", function() {
modal.style.display = "none";
});
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
champ.addEventListener("blur", verifMail);
champ.addEventListener("focus", verifMail);
function verifMail(champ)
{
var regex = /^[a-zA-Z0-9._-]+#[a-z0-9._-]{2,}\.[a-z]{2,4}$/;
if(!regex.test(champ.value))
{
surligne(champ, true);
return false;
}
else
{
surligne(champ, false);
return true;
}
}
function surligne(champ, erreur)
{ if(champ.type !="focus" && champ.type !=="blur"){
if(erreur)
{
champ.style.backgroundColor = "#fba";
document.getElementById("messageErreur").style.display ="block";
}
else
{
champ.style.backgroundColor = "";
}
}
document.getElementById("messageErreur").style.display ="none";
}
/* } */
champ.addEventListener("keyup", verifForm);
function verifForm()
{
var mailOk = verifMail(champ);
if(mailOk)
{
document.getElementById('submit1').disabled=0;
return true;
}
else
{
document.getElementById('submit1').disabled=1;
return false;
document.getElementById("messageErreur").style.display ="none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
/* Background pop-in */
.popin {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
/* Style de la pop-in */
.popin-style {
background-color: #FFFFFF;
margin: auto;
padding: 20px;
border: 1px solid #529D93;
width: 35%;
}
/* Bouton fermer */
.fermer {
color: #3f3f3f;
float: right;
font-size: 40px;
font-weight: bold;
}
.bob-style
{
width: 50%;
height: auto;
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.fermer:hover,
.fermer:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#messageErreur
{
display: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
<h2>Exemple de Pop-in</h2>
<button id="monBouton">Qui sommes nous ?</button>
<div id="maPopin" class="popin">
<div class="popin-style">
<span class="fermer">×</span>
<p>Cet objectif a été réalisé par Guillaume et Nicolas... Alias Bob et Patrick </p>
<img src="http://www.chamalow-shop.com/images/t/tds/TDS-bob-patrick-geek-vert-g.gif" class="bob-style">
<form>
<label for="email">Veuillez saisir votre email :</label>
<input type="text" name="email" id="mail" placeholder="Email...">
<button type="submit" id="submit1" disabled="disabled">Envoyer</button>
<p id="messageErreur">Adresse email incorrecte</p>
</form>
</div>
</div>
<script src="myscripts.js"></script>
</body>
</html>
champ.style.backgroundColor = "";
the background color should be set to some value, how can it be blank ?

Can't delete div from to-do list

I'm creating a to-do list app, and in the app there is a div that wraps an input box (for the to-do item and so the user can edit the to-do) and a icon from font-awesome. When the user clicks on the icon, I want the entire div (which contains the to-do and the delete icon) to be deleted. But when tried to do that, it didn't work. Can someone help me?
Here's the JS Code
$(document).ready(() => {
$(".input input").on("keypress", check_todo);
$(".fa-trash").on("click", ".todo_container", delete_todo);
})
// delete todo
let delete_todo = (e) => {
e.target.remove();
}
// add todo
let add_todo = () => {
let todo = $(".input input").val();
$(".output").append(`
<input type="text" placeholder="Edit To-do" value="${todo}"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
`);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
See the html and a demo
You should binding to .out-put container.
$(".output").on("click",".fa-trash" , delete_todo);
http://codepen.io/Vrety/pen/WoWmaE
http://codepen.io/anon/pen/eBoXZe
In your event listener, you need to swap ".todo_container" and ".fa-trash".
$(".todo_container").on("click",".fa-trash" , delete_todo);
This statement means, when a click event occurs and bubbles up to .todo_container, check if the clicked element is .fa-trash, if so call the function.
Then change your delete function
let delete_todo = (e) => {
$(e.currentTarget).closest('.todo_container').remove()
}
This code means from the clicked icon, travel up the dom to find .todo_container, then remove it.
Good job with using the delegation in JQuery but while using it
$(".todo_container").on("click",".fa-trash" , delete_todo);
The base element $(".todo_container") needs to be static, You are deleting this also in the delete_todo() function.
Try using $(".output") instead and see if it works.
here is a working code
$(document).ready(function() {
$(".input input").on("keypress", check_todo);
//$(".fa-trash").on("click", ".todo_container", delete_todo);
$(".todo_container .fa-trash").on("click", delete_todo);
})
// delete todo
let delete_todo = function(e) {
//e.target.remove();
$(e.target).parent().remove();
}
// add todo
let add_todo = function() {
let todo = $(".input input").val();
//to do container element, the delete icon will added later
var toDoContainer = $(`
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="${todo}"></div>
`);
//create delete icon and set event listener
var elem = $('<i class="fa fa-trash fa-lg" aria-hidden="true"></i>').on("click", delete_todo).appendTo(toDoContainer);
$(".output").append(toDoContainer);
$(".input input").val("");
}
// check todo
let check_todo = (e) => {
if (e.keyCode == 13) {
if ($(".input input").val() == "") {
no_todo();
} else {
add_todo();
}
}
}
// no todo
let no_todo = () => {
alert("Please add a new todo");
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Regular");
font-weight: 400
}
#font-face {
font-family: Open Sans;
src: url("assets/fonts/OpenSans-Semibold");
font-weight: 600
}
* {
margin: 0;
padding: 0;
transition: all 200ms ease-in-out;
}
*::selection {
background-color: #ffffaa;
}
.container {
width: 60%;
margin: 20px auto;
}
.header {
padding: 10px;
}
.header input {
padding: 10px;
width: 60%;
border: none;
outline: none;
font: 400 1.8em Open Sans;
}
.to-do {
padding: 10px;
text-align: center;
}
.input input {
padding: 10px;
width: 40%;
border: none;
outline: none;
font: 600 1em Open Sans;
border-bottom: 3px solid #333;
}
.output {
margin: 10px;
}
.output input {
padding: 20px;
border: none;
outline: none;
font: 600 1em Open Sans;
width: 50%;
cursor: pointer;
}
.output input:hover {
background-color: #eee;
}
.fa-trash {
padding: 20px;
cursor: pointer;
}
.fa-trash:hover {
background-color: #333;
color: #fff;
}
<head>
<title>To-do List</title>
<!-- FONTS -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,500" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="header">
<input type="text" name="edit_name" placeholder="Edit Name">
</header>
<section class="to-do">
<div class="input">
<input type="text" name="add_todo" placeholder="Click To Add A New To-do">
</div>
<div class="output">
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #1"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
<div class="todo_container">
<input type="text" placeholder="Edit To-do" value="Todo #2"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
</div>
</section>
</div>
<!-- JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://use.fontawesome.com/5840114410.js"></script>
</body>

How to take back a page to its previous state by clicking the back button of the browser in javascript

I have a page with a link to a form. After clicking the link the form shows up and the link disappears. The problem that i have is, when i click the browser's back button, the values of the URL is changed, but the state of the page doesn't go back to previous state. The form should disappear and the link shows back. Also on reload when the form is visible, the page goes back to its first state, which i need to prevent from happening.
Code :
<html>
<style>
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
</style>
<body>
<div id="categContainer1">
<div class="titimmo">Real Estate</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made"/>
<h4>Price :</h4>
<input type="text" name="modele"/><br/><br/>
</form>
</div>
<script>
function stepone() {
document.getElementById('a_categ').onclick = function () {
document.getElementById('categContainer1').className += " hidden";
document.getElementById('formContainer').className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false
};
}
stepone();
</script>
</body>
</html>
First question is: How to bring back the page to its previous state by clicking the browser's back button?
Second question is: How to prevent the page from going back to its previous state - on reload when it's on second state (when form is visible)?
There are two things you need to do to make it work:
To monitor browser back button click, use
window.onpopstate
method
To remember the form state, you need to store the value in
localStorage or in a cookie.
This is a basic example:
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
<div id="categContainer1">
<div class="titimmo">
Real Estate
</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made" />
<h4>Price :</h4>
<input type="text" name="modele" />
</form>
</div>
Also on Fiddle, where you can actually see how it works.

Categories