I am trying to use Unsubscribe() but it does not work.
var unsubscribe = firebase.auth().onAuthStateChanged((user) => {
unsubscribe()
readCourses(user.uid) //1 function
addElement(user) // 2 function
})
The first function reads data from database so the idea is to show it only once, thats why I want to stop the reading of the user info. Second function writes data on the database so it updates information. I try to stop the onAuthStateChange with unsubscribe() but when I use function 2 to get user info thats why it is inside the onAuthStateChange function, it runs again first function and duplicates the info from the database because function 1 runs again. How can I run this just once?? unsubscribe does not stop it!! Thanks I am new.I already checked. But it does now work for me.
var espacioforCards=document.getElementById('espacioCards')// Div
var nombreCurso;
var descripcionCurso;
var obtenerNombreCurso=document.getElementById('obtener nombre
curso')//button
function lecturaCursos(uid){
console.log('leyendo...datos')
var cursos = dbRef.ref("Usuarios").child(uid).child("cursos")
cursos.on('value', (snapshot) => {
if (snapshot.exists()){
//spinner
document.getElementById("spinner").style.visibility =
"visible";
//console.log(snapshot.val());
snapshot.forEach((childSnapshot) => {
crearTarjeta(childSnapshot.val().nombre,childSnapshot.val().descripcion)
})
document.getElementById("spinner").style.visibility =
"hidden";
}else{
console.log('No hay datos')
document.getElementById("spinner").style.visibility =
"hidden";
}
});
}
function crearCurso(userRef,nombreCurso,descripcionCurso){
userRef.child(
'cursos').update({[nombreCurso]:{'nombre': nombreCurso,
'descripcion': descripcionCurso}})
}
function crearTarjeta(nombreCurso,descripcionCurso){
let card = document.createElement("div")
card.setAttribute("class","card")
card.setAttribute('style', 'width: 15rem; margin:5px')
card.setAttribute("id", nombreCurso);
card.innerHTML+='<img src="img/nuevosm.jpg"class="card-img-top"
alt="..."></img>'
let cardbody = document.createElement("div")
cardbody.innerHTML+= '<h5 class="card-title">'+nombreCurso+'</h5>'
cardbody.innerHTML+= '<p class="card-text">'+descripcionCurso+'</p>'
cardbody.innerHTML+='al curso'
card.appendChild(cardbody)
espacioforCards.appendChild(card)
}
function addElement (user) {
console.log('adding elements...........')
obtenerNombreCurso.addEventListener("click", function(){
nombreCurso=document.getElementById('nombre del curso').value
descripcionCurso=document.getElementById('descripcion del
curso').value
if(Boolean(nombreCurso) && Boolean(descripcionCurso)){
crearTarjeta(nombreCurso,descripcionCurso)
let userRef=dbRef.ref('Usuarios').child(user.uid)
crearCurso(userRef,nombreCurso,descripcionCurso)
//location.reload(true)
}else{
console.log('you must fill in')
}
})
}
Related
I am making a small website and I need to save the state of the page after refreshing. I have the following javascript code where I have used local storage to store the inputs with setItem. They get stored just fine, however I'm not sure how to retrieve them.
window.addEventListener('load', () => {
todos = JSON.parse(localStorage.getItem('todos')) || [];
const form = document.querySelector("#listForm");
const input= document.querySelector("#newElement");
const listTask= document.querySelector("#tasks");
form.addEventListener('submit', (e) =>{
e.preventDefault();
const task=input.value;
const taskElement = document.createElement('div');
taskElement.classList.add('task');
if(!task){
alert("You need to write something!");
return;
}
todos.push(task);
localStorage.setItem('todos', JSON.stringify(todos));
const taskContentEl= document.createElement('div');
taskContentEl.classList.add('content');
taskElement.appendChild(taskContentEl);
const taskInputEl=document.createElement('input');
taskInputEl.classList.add('text');
taskInputEl.type='text';
taskInputEl.value= task;
taskInputEl.setAttribute('readonly','readonly');
taskContentEl.appendChild(taskInputEl);
listTask.appendChild(taskElement);
const taskActionsEl= document.createElement('div');
taskActionsEl.classList.add('actions');
const editEl= document.createElement('button');
editEl.classList.add('edit');
editEl.innerText='Edit';
const doneEl= document.createElement('button');
doneEl.classList.add('done');
doneEl.innerText='Done?';
taskActionsEl.appendChild(doneEl);
const deleteEl= document.createElement('button');
deleteEl.classList.add('delete');
deleteEl.innerText='X';
taskActionsEl.appendChild(editEl);
taskActionsEl.appendChild(deleteEl);
taskElement.appendChild(taskActionsEl);
input.value='';
editEl.addEventListener('click', (e) => {
if(editEl.innerText.toLowerCase() == "edit"){
editEl.innerText="Save";
taskInputEl.removeAttribute("readonly");
taskInputEl.focus();
}
else {
editEl.innerText="Edit";
taskInputEl.setAttribute("readonly","readonly");
}
});
doneEl.addEventListener('click', (e) => {
if(doneEl.innerText.toLowerCase()=='done?'){
doneEl.innerText='✔';
taskContentEl.classList.add('checked');
}
else{
doneEl.innerText="Done?"
taskContentEl.classList.remove('checked');
}
});
deleteEl.addEventListener('click', (e) => {
listTask.removeChild(taskElement);
todos.pop(task);
localStorage.setItem('todos', JSON.stringify(todos));
})
localStorage.getItem('todos');
});
});
I tried using JSON.parse like this, but I'm not sure why it's not working, or where to put it.
JSON.parse(localStorage.getItem('todos'));
I have made this phone book site where it stores for now the name and the phone number of the user.
Now I have hit a wall where if I insert the user data (name and phone number) it pushes it to the phone book array and when I try to push another user it replaces the first one instead of updating the array.
This is my JavaScript code:
"use strict";
let myStorage = window.localStorage;
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
}
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
}
cancelOverlay("cancelOverlay", "formContainer");
function inputAndOutput() {
cancelOverlay("submitButton", "formContainer"); //this function helps me close the form window after i click on send
const form = document.getElementById("addForm");
form.addEventListener("submit", (e) => { //this is a submit event when the send button is pressed it makes an object and with the help of JSON it puts it into an array
let formOutput = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
} //end of form
myStorage.setItem("formOutput", JSON.stringify(formOutput)); //array of obj
console.log(myStorage.getItem('formOutput')); //testing
displayOutput();
e.preventDefault(); //prevent the page to reload
} //end of Event
, );
}
inputAndOutput();
let phoneArray = [100];
function displayOutput() {
if (myStorage.getItem('formOutput')) {
let { name, phoneNumber } = JSON.parse(myStorage.getItem('formOutput'));
const output = document.getElementById("outPutContainer");
phoneArray.push(output.innerHTML =
`
<ul>
<li>${name} </li>
<li>${phoneNumber} </li>
</ul>
<br>
`);
}
}
As you are submitting the form you are just replacing the localstorage item with the new one instead of that you will have to take the value from the storage store it in a variable and then add the new values to the same variable and push that variable to the storage.
some what like this:
form.addEventListener("submit", (e) => { //this is a submit event when the send button is pressed it makes an object and with the help of JSON it puts it into an array
let formOutput = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
} //end of form
//HERE
const oldData = JSON.parse(myStorage.getItem("formOutput"));
oldData.push(formOutput); // I believe its an array
myStorage.setItem("formOutput", JSON.stringify(oldData)); //array of obj
console.log(myStorage.getItem('formOutput')); //testing
displayOutput();
e.preventDefault(); //prevent the page to reload
} //end of Event
, );
My problem is that I can't stop executing a function and it is causing me a big problem. This function is a function that I perform when the modal is opened and it is waiting for me to submit the form to register or update the data. The problem is that every time I close and open this modal, it executes the function depending on how many times I opened this modal. For example: if I open the modal for the first time, register and close. If I open it again, it will register the value I enter and it will register again but an empty data. My code is a bit long because I split it up to be able to optimize it. I'm using the "realtime database", from firebase
This is the code for the floating buttons. I click on a button and it shows another two buttons, one for registering categories and another for products. Clicking on any of them opens a specific modal
function modalFloatButtons_options() {
let floatButtonAdd = document.getElementById("carte_modalFloatAddBtn");
let modalFloatButtonsOptions = document.querySelector(".modalFloatButtons_options");
modalFloatButtonsOptions.style.display = "none";
// Functions
// Open or close div
function openCloseOptions() {
floatButtonAdd.addEventListener("click", (e) => {
if(modalFloatButtonsOptions.style.display == "none"){
modalFloatButtonsOptions.style.display = "block";
optionsAnimation_openClose("block");
modalFloatButton_options_btnsEnvetListener()
}else{
optionsAnimation_openClose("none");
setTimeout(() => {
modalFloatButtonsOptions.style.display = "none";
}, 251);
}
})
}openCloseOptions()
// Options animation
function optionsAnimation_openClose(display) {
if(display == "block"){
modalFloatButtonsOptions.animate([
{ bottom: '10%' },
{ bottom: '120%' }
], {
duration: 250,
})
}else{
modalFloatButtonsOptions.animate([
{ bottom: '120%' },
{ bottom: '0%' }
], {
duration: 250,
})
}
}
// Float buttons - options - event listener
function modalFloatButton_options_btnsEnvetListener() {
let modalFloatButtonOptionsBtn = document.querySelectorAll(".modalFloatButtons_options_btn");
modalFloatButtonOptionsBtn.forEach(element => {
element.addEventListener("click", (e) => {
modal_openModal(e.target.id.substr(4), "create")
})
});
}
}modalFloatButtons_options()
// Open modal
function modal_openModal(id, method, data, key) {
let div = document.getElementById(id);
div.style.display = "flex";
modal_closeModal(div, id);
if(id == "modalCategory"){
modalAddCategory("execute", method, data, key)
}else if(id == "modalProduct"){
}
}
// Close modal
function modal_closeModal(div, id) {
let closeBtn = document.querySelector("#"+id+" .modal_closeBtn");
div.addEventListener("click", (e) => {
if(e.target.id === div.id || e.target.classList[1] === "modal_closeBtn"){
div.style.display = "none";
modalAddCategory("break")
}
})
}
When he clicks the button, he will see the id and execute the function
function modalAddCategory(execute, method, updateData, key){
let form = document.querySelector("#modalCategory form");
let submitbtn = document.querySelector("#modalCategory form button");
let categoryInput = document.querySelector("#modalCategory form input[name='categoryTitle']");
// Putting value in the input if it is for update
if(method == "update"){
categoryInput.value = updateData.category
}
console.log(method)
console.log("--------")
// Event listener - submit btnm
realtimedb_eventSubmitBtn(submitbtn, categoryData, form);
// Data
function categoryData() {
let data = {
category: categoryInput.value
};
// Register data
if(method == "update"){
realtimedb_update("Categories", data, key)
}else if(method == "create") {
realtimedb_create("Categories", data);
}
}
}
And it is and the function that is giving me trouble
// Event listener - submit btn
function realtimedb_eventSubmitBtn(btn, nameFunction, form) {
btn.addEventListener("click", (element) => {
element.preventDefault();
nameFunction();
form.reset();
})
}
I tried to use return but it didn't work, someone please help me
I have a following trouble in APIFY. I would like to write a function that saves HTML body of a current page and then click to the next page, saves HTML body etc.
I tried this:
var result = [];
var scrapeAndClick = function() {
$("div.ui-paginator.ui-paginator-top.ui-widget-header.ui-corner-top").each(function() {
result.push(
$(this).html()
);
//klikej na dalsi stranky
var nextButton = $('a.ui-paginator-next.ui-state-default.ui-corner-all');
console.log('Click next button');
nextButton.click().delay(4000)
});
};
scrapeAndClick();
In Google Chrome console it returns me only the HTML body of the first page. APIFY does not return anything.
Can someone see, where is the problem?
If is someone interested in the whole Page function:
async function pageFunction(context) {
const { log } = context;
const searchSelector = 'div.ui-panel-content.ui-widget-content > button';
//vyber "Gemeenschappelijk Landbouw Beleid" z Kies subsidie:
const subsidySelector = $("span.column2 > select.jsTruncate").val("10000");
log.info('Select CAP ')
subsidySelector
//klikni na Zoek
log.info('Click search.')
$(searchSelector).eq(0).click()
//loopujeme dalsi stranky a ukladame html body
var result = [];
var scrapeAndClick = function() {
$("div.ui-paginator.ui-paginator-top.ui-widget-header.ui-corner-top").each(function() {
result.push(
$(this).html()
);
//klikej na dalsi stranky
var nextButton = $('a.ui-paginator-next.ui-state-default.ui-corner-all');
console.log('Click next button');
nextButton.click().delay(4000)
});
};
scrapeAndClick();
return result;
}
StartURL is this: https://mijn.rvo.nl/europese-subsidies-2017
I found an old question on APIFY forum (https://forum.apify.com/t/clickable-link-that-doesnt-change-the-url/361/3), however it seems that it was done on old version of APIFY crawler.
Thanks a lot for any help!
I have the following code in js:
function feed() {
if(!batut){
foods.forEach(food => {
food.addEventListener('click', function() {
reset();
imgs[first + 1].style.display = "block"
txt.innerHTML = "Boss e satul. Doarme ca un porc."
feedTime();
} )
})
}
}
function goesAway(){
reset();
imgs[2].style.display = "block";
txt.innerHTML = "L-ai batut pe Boss si pleaca!"
clearTimeout(timer);
batut = true;
}
First one displays another img when i click one each of the objects.
The second is a function that triggers when i press a button.
When that happens i don't want that the first function to work anymore so I put there var = true in order to change it and dosn't apply to the if in the first but is not working..can someone help?