I can't stop executing a function - javascript

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

Related

Remove a JavaScript class method from eventlistener inside another method of the same class

Description & Goal
I have a list with items and clicking on an item shows a detail view, shows a close button and add the eventlistener for closing this item to the button.
By clicking on this button the detail view should be closed and the eventlistener should be removed.
I can't use an anonymous function because removing won't work with it (See here and here).
Problem
Removing doesn't work.
Code
export default class ToggleDetails {
constructor(jobAdId) {
this.jobAdId = jobAdId
this.opened = false
}
toggle() {
const jobAdContainer = document.getElementById(this.jobAdId)
// doing some other css manipulation for the detail view
this.handleCloseButton()
}
handleCloseButton() {
const closeButton = document.getElementById('uh-job-detail-close-button')
const $this = () => {
this.toggle()
}
if (this.opened === true) {
closeButton.classList.remove('uh-job-detail-close-button-show')
closeButton.removeEventListener('click', $this)
this.opened = false
} else {
closeButton.classList.add('uh-job-detail-close-button-show')
closeButton.addEventListener('click', $this)
this.opened = true
}
}
}
HTML structure
"Solution"/Workaround
I solved it, by cloning and replacing the button with itself. The clone doesn't have the eventlisteners (Thanks to this post)
handleCloseButton () {
const closeButton = document.getElementById(
'uh-job-detail-close-button')
closeButton.classList.toggle('uh-job-detail-close-button-show')
if (this.opened === true) {
const elClone = closeButton.cloneNode(true)
closeButton.parentNode.replaceChild(elClone, closeButton)
this.opened = !this.opened
} else {
closeButton.addEventListener('click',
() => { this.toggle() })
this.opened = !this.opened
}
}
Try using a named function and passing the value of this into toggle:
export default class ToggleDetails {
constructor(jobAdId) {
this.jobAdId = jobAdId
this.opened = false
}
toggle(t) {
// doing some other css manipulation for the detail view
t.handleCloseButton()
}
handleCloseButton() {
const closeButton = document.getElementById('uh-job-detail-close-button')
let listenerToggle = () => {
this.toggle(this);
};
if (this.opened === true) {
closeButton.classList.remove('uh-job-detail-close-button-show')
closeButton.removeEventListener('click', listenerToggle)
this.opened = false
} else {
closeButton.classList.add('uh-job-detail-close-button-show')
closeButton.addEventListener('click', listenerToggle)
this.opened = true
}
}
}

Reload page after click OK on the Alert Page

I want to reload page after clicking OK button on the javascript Alert box.
Here is my code :
$(".erase").click(function () {
var answer = confirm("Delete This Data?");
if (answer === true) {
var erase = false;
if (!erase) {
erase = true;
$.post('delete.php', {id: $(this).attr('data-id')} );
erase = false;
}
window.location.reload();
} else {
return false;
}
});
if I put the window.location.reload(); there, the page reloading after click OK, but I can't delete the data I want.
If I remove it, I can delete the data but the page doesn't reload.
Please help me on this
You just need to provide the window.reload() as a callback to $.post.
$(".erase").click(function () {
var answer = confirm("Delete This Data?");
if (answer === true) {
var erase = false;
if (!erase) {
erase = true;
$.post('delete.php', {id: $(this).attr('data-id')}, function() { // here's the new bit
window.location.reload();
} );
erase = false;
}
} else {
return false;
}
});
Change your first line to (I write code from head):
$(".erase").click(async function () {
and line with $.post to this:
let postResult = await Promise.resolve($.post('delete.php', {id: $(this).attr('data-id')} ));

How can I trigger modal boxes using the following javascript code?

Hey guys I need just a little bit of help with this.
So I have modal boxes hiding on my page and when I click on them using the video platform VERSE they work perfectly.
My questions is: How can I call the same modal boxes if I wan to call them from a regular link or button on the page.
Here is the sample:
http://digitalfeast.com/clients/nccv/ncc-verse.html
Here is my Javascript code:
(function() {
(function() {
window.onload = function() {
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
// Variables below (i.e. "menu-1") reference div id from your markup
function receiveMessage(event) {
var data = (typeof event.data === "String") ? JSON.parse(event.data) : event
var modalWindow1 = document.getElementById("ruben-1");
var modalWindow2 = document.getElementById("ruben-2");
var modalWindow3 = document.getElementById("menu-3");
var modalWindow4 = document.getElementById("menu-4");
// Variables below (i.e. "menu-1") reference the unique callback names entered for your hotspots in the Verse editor
if (data.data["identifier"] === "ruben-1") {
modalWindow1.style.display = "block";
}
if (data.data["identifier"] === "ruben-2") {
modalWindow2.style.display = "block";
}
if (data.data["identifier"] === "menu-3") {
modalWindow3.style.display = "block";
}
if (data.data["identifier"] === "menu-4") {
modalWindow4.style.display = "block";
}
}
var closeBtns = document.getElementsByClassName("modal-close");
for (var i = 0; i < closeBtns.length; i++) {
var btn = closeBtns[i];
btn.onclick = function (event) {
event.target.parentNode.parentNode.style.display = "none";
frame.postMessage({action: "play"}, "*");
};
}
window.addEventListener('message', receiveMessage);
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
};
}());
}());
Given your code, all you need to do is send the window a message using the Messaging API inside your button click handler.
Your event listener will then execute the receiveMessage function and open your model for ruben-1.
window.onload = () => {
document.querySelector('[data-modal="ruben-1"]').addEventListener("click", (e) => {
let postData = {
identifier: e.target.dataset.modal
};
window.postMessage(postData, "*");
});
window.addEventListener('message', m => {
alert(m.data.identifier);
});
}
<button data-modal="ruben-1">Ruben-1 Video</button>

jquery draggable revert programmatically

I am currently developing a calendar where activities can be drag&dropped to other days.
When an activity is dropped into a different day, I show a custom modal using durandal's dialog plugin. The problem is when an user closes the modal, the activity has to revert to its original position. When an activity is dropped the following code is called:
function showDroppedActivityModal(obj) {
require(['modals/droppedActivityModal/droppedActivityModal', 'moment'], function(droppedActivityModal, moment) {
droppedActivityModal.show(obj).then(function(response) {
if(response !== false) {
...
}
// dialog closes
else {
calendarView.revertActivity.notify({ revert: true})
}
});
});
}
In my calendarView I implemented the revertActivity event to set revert to true but the function never re-evaluates itself but i'm able to receive the new revert value (true).
$(activity).draggable({
revert: function() {
var revert = false;
self.revertActivity.attach(function(sender, args) {
revert = args.revert;
});
return revert;
}
});
Custom event code:
function CalendarEvent(sender) {
this._sender = sender;
this._listeners = [];
}
CalendarEvent.prototype = {
attach : function (listener) {
this._listeners.push(listener);
},
notify : function (args) {
var index;
for (index = 0; index < this._listeners.length; index += 1) {
this._listeners[index](this._sender, args);
}
},
remove : function (listener){
this._listeners.remove(listener);
}
};
this.revertActivity = new CalendarEvent(this);

Panel Visibility via JS

The tutorial at http://www.asp.net/web-forms/tutorials/ajax-control-toolkit/getting-started/creating-a-custom-ajax-control-toolkit-control-extender-vb gives a nice example of a custom extender based on a textbox and a button. Basically the button remains disabled until at least one character is typed into the textbox. If the text is removed from the textbox the button is disabled again.
I am trying to modify this so that the extender is based on a textbox and panel. Again I want the panel to become visible when text is present in a textbox.
This is how I amended code...
Type.registerNamespace('CustomExtenders');
CustomExtenders.ShowHidePanelBehavior = function (element) {
CustomExtenders.ShowHidePanelBehavior.initializeBase(this, [element]);
this._targetPanelIDValue = null;
}
CustomExtenders.ShowHidePanelBehavior.prototype = {
initialize: function () {
CustomExtenders.ShowHidePanelBehavior.callBaseMethod(this, 'initialize');
// Initalization code
$addHandler(this.get_element(), 'keyup',
Function.createDelegate(this, this._onkeyup));
this._onkeyup();
},
dispose: function () {
// Cleanup code
CustomExtenders.ShowHidePanelBehavior.callBaseMethod(this, 'dispose');
},
// Property accessors
//
get_TargetPanelID: function () {
return this._targetPanelIDValue;
},
set_TargetPanelID: function (value) {
this._targetPanelIDValue = value;
},
_onkeyup: function () {
var e = $get(this._targetPanelIDValue);
if (e) {
var visibility = ("" == this.get_element().style.value);
e.visibility = 'visible';
}
}
}
CustomExtenders.ShowHidePanelBehavior.registerClass('CustomExtenders.ShowHidePanelBehavior', Sys.Extended.UI.BehaviorBase);
When run the panel will not appear. No errors are produced.
Where have I gone wrong...
Try this code:
_onkeyup: function () {
var panel = $get(this.get_TargetPanelID());
if (panel) {
var visibilityValue = ("" == this.get_element().value) ? "hidden" : "visible";
panel.style.visibility = visibilityValue;
}
}

Categories