Global variable scope with event handler for dynamically created element - javascript

I want to change the behaviour of a Bootstrap dropdown based on a global state variable. If the uiState variable is 'normal' when it is clicked, it should display the dropdown, but if it's in another state it should do something else. I have the following code:
$(document).ready(function () {
var uiState = 'normal';
// Load HTML for word control from server
var wordUiElement;
$.get('/static/word_ui_element.html', function (data) {
wordUiElement = data;
});
var nwords = 0;
var testClickCounter = 0;
// Make it so dropdowns are exclusively controlled via JavaScript
$(document).off('.dropdown.data-api')
$('#ui-add-word').click(function (event) {
var control = wordUiElement.replace(/wx/g, 'w' + nwords.toString());
$('#ui-spec').append(control);
nwords++;
});
$('#ui-change-state').click(function (event) {
if (uiState === 'word_select') {
uiState = 'normal';
} else {
uiState = 'word_select';
}
console.log(uiState);
});
$('#ui-spec').on('click', '.dropdown .dropdown-toggle', function (event) {
if (uiState === 'normal') {
$(this).dropdown('toggle');
}
else {
testClickCounter ++;
console.log(testClickCounter);
}
});
});
However, when the dropdowns are dynamically created, their behaviour seems to be fixed based on what the uiState variable was when the dropdown was created.
This means that if a dropdown was created when the uiState variable was set to 'normal', no matter what uiState is when it's clicked, it will always show or hide the dropdown. On the other hand if the dropdown was created when uiState was 'word_select', it will always increment and log testClickCounter. It's as if the if statement in the handler is evaluated once when the dropdown is created and preserves whatever the value of uiState was when it was created.
I assume this is a scoping issue, and the event handler is executed when it's created. I want it to check at the time of the click what the value of uiState is, but I don't know how to fix it.

Instantiate the element with data-toggle="dropdown" and remove this property when it changes state, eg:
$('#wx').attr('data-toggle',''); // Dropdown no longer shows
or
$('#wx').attr('data-toggle','dropdown'); // Dropdown shows again
The rest of the trigger continue as usual:
$('#wx').on('click', '.dropdown .dropdown-toggle', function (event) {
if (uiState !== 'normal') {
testClickCounter ++;
console.log(testClickCounter);
}
});

Related

Multiple Javascript Event Listener Issues

Background info: I'm using WooCommerce and Gravity Forms, and trying to make it so the Add to Cart button is inactive according to two conditions - either there are no attendees registered, or the date hasn't been selected from the product variation dropdown. The user should only be able to move forward if both sections are completed.
The Gravity Forms component of this has a popup module to sign up those attendees, but the summary is displayed outside the module and on the main product page. The class .gpnf-no-entries lives on the "outside" of the Gravity Forms module, since it's always visible on the page. .gpnf-nested-entries and .gpnf-row-actions are also outside the module, but rely on information from within the module. .tingle-btn is a class used on multiple buttons inside the module - to add an attendee, cancel editing, or delete that attendee (unsure if I need a loop on here - alerts were working without one, and it seems like there's something else causing issues regardless).
Issues: It was working at one point, but only after the second click (anywhere on the page). There's also a second issue - on this form, if you've added an attendee but not added the product to the cart, the page retains any info you've put in. So what happens is, if you refresh the page and have old attendee info already there, the Add to Cart never gets clickable after selecting a date, even though both areas are filled out.
Screenshots:
I'm still somewhat of a beginner here so it's quite possibly something silly.
<script>
var modalButtons = document.querySelectorAll('.tingle-btn');
var noEntries = document.querySelector('.gform_body .gpnf-no-entries');
var entryField = document.querySelectorAll(".gpnf-nested-entries .entry-field[style='display: block;']");
var nestedEntriesDelete = document.querySelector('.gpnf-row-actions .delete');
var addToCart = document.querySelector('.single_add_to_cart_button');
var wcVariation = document.querySelector('.woocommerce-variation-add-to-cart');
var selectCheck = document.querySelector('#select-date-option');
//When date selection dropdown is changed, check value and check for "no entries" message
document.addEventListener('change', function (event) {
if (!event.target.matches('selectCheck')) {
if ((noEntries.style.display !== 'none') || (selectCheck.value === '')) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
else {
addToCart.classList.remove('disabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
// When attendee is deleted, check to see if there are any entry fields left
document.addEventListener('click', function (event) {
if (!event.target.matches('nestedEntriesDelete')) {
if (entryField.length <= 3) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
// Check for "no entries" and no date selection value when buttons to add or remove attendees are clicked
document.addEventListener('click', function (event) {
if (!event.target.matches('modalButtons')) {
if ((noEntries.style.display !== 'none') || (selectCheck.value === '')) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
else {
addToCart.classList.remove('disabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
</script>
I ended up doing this a much simpler way by adding classes:
<script>
var noEntries = document.querySelector('.gform_body .gpnf-no-entries');
var entriesContainer = document.querySelector('.gpnf-nested-entries-container');
var addToCart = document.querySelector('.single_add_to_cart_button');
//When page is fully loaded, check for cached entries
window.addEventListener('load', function () {
//if there are entries, show the add to cart button
if (noEntries.style.display === 'none'){
entriesContainer.classList.add('has-entries');
addToCart.classList.add('do-add');
addToCart.classList.remove('dont-add');
}
//if there are no entries, disable the add to cart button
else if (noEntries.style.display === ''){
entriesContainer.classList.remove('has-entries');
addToCart.classList.add('dont-add');
addToCart.classList.remove('do-add');
}
//if the form isn't present, don't do any of this
else if (noEntries = 'null'){
//do nothing
}
});
//When the container with the form and the entries is clicked, check for entries
document.addEventListener('click', function (event) {
if (!event.target.matches('#gform_wrapper_41')) {
setInterval(function() {
//if an entry is added, show the add to cart button
if (noEntries.style.display === 'none'){
entriesContainer.classList.add('has-entries');
addToCart.classList.add('do-add');
addToCart.classList.remove('dont-add');
}
//if all entries are removed, disable the add to cart button
else if (noEntries.style.display === ''){
entriesContainer.classList.remove('has-entries');
addToCart.classList.add('dont-add');
addToCart.classList.remove('do-add');
}
},2000);
}
}, false);
</script>

Enable and disable onclick funtion

I am dynamically creating a table where i am adding onclick function to each column.
for (var x = 0; x < r.length; x++) {
//Setting the columns
if (i === 1) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = r[x];
headerCell.id = x;
headerCell.onclick = function () {
sortTable(this.id, name);
}
row.appendChild(headerCell);
}
}
In a specific situation I want to disable the onclick function. Here is the code and it works.
$('#errorTable TH').prop("onclick", null).off("click");
and in another situation i want to reattach the onclick function. And that doesn't work. I want to enable the original function....
Any ideas ?
The way you created your table and adding/removing events are not easily maintainable. I also have some suggestions:
Review your code and define code click handler separately.
If you use jQuery in your project use it every where, if not, do not use it anywhere.
In your code i is undefined.
Add Remove Event Listener with jQuery
First define your handler function:
var myClickHandler = function(){
// this is your click handler
alert('Yes!!!');
}
Select your element and assign to a variable. <div id="clickable">Click Me!</div> must be in the DOM at the time of below script executed.
var element = $('#clickable');
// assign event listener
element.on('click',myClickHandler);
// remove event listener:
element.off('click',myClickHandler);
note that you must have to inform jQuery which handler should be removed.
See a sample https://codepen.io/softberry/pen/BEpove
An alternative is to build a click handler that checks a "kill switch".
var tableClickable = true;
headerCell.onclick = function () {
if (tableClickable) {
sortTable(this.id, name);
}
}
//In a specific situation I want to disable the onclick function.
something.addEventListener('someEvent', function () {
tableClickable = false;
});
//and in another situation i want to reattach the onclick function.
something.addEventListener('someOtherEvent', function () {
tableClickable = true;
});

AngularJS: Write inside input box via JS, Do not transfer the value in the JSON

Background: I have an external device (barcode reader) that sends information back to a tablet when the user scans something. I subscribe to that channel and I need the value to be inside the currently focused cell and write it there.
Bug: I can catch the subscription and write the value visually in the Input box, but it never reaches the JSON underneath.
I also tried $scope.$apply() but it did not change anything (maybe I used it wrong).
"Working" Plunker with the problem
$scope.randomClickOnStuff = function() {
// Here Randomely publish stuff with value so we can write it in specific field.
window.setTimeout(function() {
if (!$scope.stopMe) {
vm.objectOtSubscribeTo.publish(channelToUse, Date.now());
$scope.randomClickOnStuff();
} else {
// Stop the loop.
}
}, 1000);
};
var callbackCompleted = function(resultValue) {
// Important code Here
// Code to write in the input box here.
console.log(resultValue);
if (document.activeElement.localName == "input") {
// Option 1:
//--> Work Visually <-- but do not put the value inside the JSON.
document.activeElement.value = resultValue;
$scope.$apply();
// Option 2:
// http://stackoverflow.com/questions/11873627/angularjs-ng-model-binding-not-updating-when-changed-with-jquery
// Problem: The "document.activeElement.attributes['ng-model'].value" is not link with the scope, but with the ng-repeat row. So I have access to the Scope, but not the Row item.
//var binding = document.activeElement.attributes['ng-model'].value;
// Rule: I might not know where the Item is so I cannot do $scope.complexObject[row][binding]
} else {
console.log("not inside a Input box.");
}
};
vm.objectOtSubscribeTo.subscribe(channelToUse, callbackCompleted);
Thanks
One solution would be to keep track of the selected row and cell by setting them on focus of one of the cells
$scope.focusedRow = false;
$scope.focusedCell = false;
$scope.setFocused = (row, cell) => {
$scope.focusedRow = row;
$scope.focusedCell = cell;
};
/* In callback... */
if ($scope.focusedRow !== false && $scope.focusedCell !== false) {
$scope.$apply(
() => $scope.complexObject[$scope.focusedRow]
["cellInTheRow"][$scope.focusedCell] = resultValue
);
}
<input type="text" ng-model="row.cellInTheRow[key]"
ng-focus="setFocused(rowKey, key)" ng-blur="setFocused(false, false)">
Example: https://plnkr.co/edit/och5PoepJuRde0oONIjm?p=preview

Should event handlers be the last statement in a method?

I have a method which is called onClick of some element. In that function I have an event handler( JQuery $().click() ), that detects the click of a button and performs some action.
I have noticed that the event handler works fine as long as it is the last block of statement in the function and is skipped altogether if there lie certain code block after it. Why is that happening?
EDIT Adding code
function launchPopUp(ID) {
if ($('#popUp').is(':hidden')) {
var serial = ID.id; // ID of the element or area clicked.
var headData = 'SVG PopUp';
var entData = 'Enter the data you want to store:';
var ok = "No";
var input = "";
var header = addHeader(headData);
var enterable = addEnterable(entData);
var buttons = addButtons();
$('#popUp').append(header);
$('#popUp').append(enterable);
$('#popUp').append(buttons);
$('#popUp').show();
$('#btnSubmit').click(function() {
input = document.getElementById('txtData').value;
if (input != "") {
ok = "yes";
$(ID).css('fill', 'green'); // Change colour to green only if some valid data is entered.
closePopUp();
}
});
var collData = { "ID": serial, "header": headData, "OK": ok, "input": input };
collection.push(collData);
}
}
Control is jumping straightaway to the code block after the .click()
You are misunderstanding the event handlers.
Javascript has asynchronous nature, so (in normal cases) there is no "waiting" for an event.
You register an eventhandler like your click() and then the function is executed when (eventually) a click on that element is registered. In the meantime the execution of the rest of your code goes on.
If you want to make your code dependent on the click, you have to write this code into the function of the click handler or pass a callback to the function.
Registering Event-Handlers is a one-time process and has to be done outside your function - at the moment you are registering a new click-handler every time you call launchPopUp. E.g. if you are calling launchPopUp five times, your code
input = document.getElementById('txtData').value;
if (input != "") {
ok = "yes";
$(ID).css('fill', 'green');
closePopUp();
}
also gets executed five times as soon as you click on #btnSubmit.
Basically you have to structure your code like the following:
register eventhandler for #btnSubmit - define what is happening when the button is clicked in this function (evaluation of your inputs)
write the launchPopUp function which gets eventually executed. No eventhandler in here and no evaluation code on btnSubmit this is all done in your eventhandler.
I think this is what you want:
function launchPopUp(ID) {
if ($('#popUp').is(':hidden')) {
var serial = ID.id; // ID of the element or area clicked.
var headData = 'SVG PopUp';
var entData = 'Enter the data you want to store:';
var ok = "No";
var input = "";
var header = addHeader(headData);
var enterable = addEnterable(entData);
var buttons = addButtons();
$('#popUp').append(header);
$('#popUp').append(enterable);
$('#popUp').append(buttons);
$('#popUp').show();
var collData = { "ID": serial, "header": headData, "OK": ok, "input": input };
collection.push(collData);
$('#btnSubmit').click(function() {
input = document.getElementById('txtData').value;
if (input != "") {
collData.OK = "yes";
$(ID).css('fill', 'green'); // Change colour to green only if some valid data is entered.
closePopUp();
}
});
}
}
Note that the collData is a variable containing a reference to an object. That object is added to the collection, and modified within the click handler when the btnSubmit button is clicked. This way, if the save button is never clicked, the object is still added to the collection. But if it is clicked, the object is changed, and closePopUp() is called, presumably allowing you to do what you need to do with the objects which exist in the collection variable.
$('#btnSubmit').click(function() {
input = document.getElementById('txtData').value;
if (input != "") {
ok = "yes";
$(ID).css('fill', 'green'); // Change colour to green only if some valid data is entered.
closePopUp();
}
});
Put the above outside your loadPopup function and put it in a
$(document).ready(function()
{
});
That might just solve it.
EDIT:
$('#btnSubmit').click(function()
{
input = document.getElementById('txtData').value;
if (input != "")
{
ok = "yes";
$(ID).css('fill', 'green'); // Change colour to green only if some valid data is entered.
closePopUp();
}
var collData = { "ID": serial, "header": headData, "OK": ok, "input": input };
collection.push(collData);
});
var collData should be IN your click function, then it will be executed when you click on the submit button.
The above code will not work good if I understand it correctly. It looks like every time you launch the popup you bind a new click event to it. So if you launch the same popup twice you will have two on click event handlers bound to the object.
Accessing variables outside the closure is practical. However, you can only access the variables that has been defined before you define your closure.
Imagine that you move the definition of "ok" after you define your click event handler. In that case OK would not be defined and there will be another ok in the event handler.
(I hope I understood your question correct, please comment otherwise)
Try this:
var launchPopUp = function launchPopUp(ID) {
'use strict';
var popup = $('#popUp'), //cache #popup instead of doing multiple lookups
headData = 'SVG PopUp',
entData = 'Enter the data you want to store:',
submit = null, //declare a var to cache #btnSubmit instead of doing multiple lookups
submitHandler = function (e) { //handler can be defined anywhere in this routine
//collData should be defined in the handler
var collData = {
"ID": ID.id, // ID of the element or area clicked.
"header": headData,
"OK": "No",
"input": document.getElementById('txtData').value
};
//modify collData based on inputs at time #btnSubmit is clicked.
if (collData.input !== "") {
collData.OK = "yes";
$(ID).css('fill', 'green'); // Change colour to green only if some valid data is entered.
closePopUp();
}
collection.push(collData);
};
if (popup.is(':hidden')) {
popup.append(addHeader(headData));
popup.append(addEnterable(entData));
//if addButtons() defines/creates/adds #btnSubmit then you will need
//to attach the handler after #btnSubmit exists in the DOM
popup.append(addButtons());
//once #btnSubmit is in the DOM, you can add the handler at any time
//although I recommend doing it prior to showing #popup
submit = $('#btnSubmit'); //cache #btnSubmit
if (!submit.data('handlerAttached')) {
//only need to attach the handler one time.
//also note that attaching the handler does not fire the handler
//only clicking the button, or calling the handler (i.e., submit.click()
//or submitHandler(), etc.) will fire the handler.
submit.click(submitHandler);
//set flag to indicate that the handler has been attached.
submit.data('handlerAttached', true);
}
popup.show();
}
};
Also, as long as these are all defined elsewhere:
addEnterable()
addButtons()
addHeader()
closePopUp()
collection[]
your routine shouldn't have any errors preventing execution of the handler.

AJAX addEventListener - passing parameters to another function

I'll keep this short - I've got a list of buttons, that I create using a loop, and when one of them gets clicked I want to be able to pass its id attribute to another file in order to dynamically generate a new page.
Here's the code:
for (var i in data.contacts) {
var temp = document.createElement('div');
temp.className = "contacts";
var dude = document.createElement('input');
dude.type = "button";
dude.value = data.contacts[i];
dude.id = data.contacts[i];
dude.className = "dude_button" + data.contacts[i];
dude.addEventListener('click', function(event) { gotoProfile(dude.id); }, false);
temp.appendChild(dude);
temp.appendChild(document.createElement('br'));
theDiv.appendChild(temp);
}
// and now in another file, there's gotoProfile():
function gotoProfile(x) {
var username = document.getElementById(x).value;
if (xmlHttp) {
try {
.... etc.
Now see this works, sort of, but the problem is that when I click any button, it only passes the last dude.id value from the list data.contacts. Obviously I want every button's addEventListener to pass its own data.contacts[i] value, instead of just the last one.
Help appreciated, thanks guys.
Because JavaScript has no block scope, dude will refer to the last assigned element (because the loop finished) when the event handler is called. You have to capture the reference to the current dude by e.g. using an immediate function:
dude.addEventListener('click', (function(d) {
return function(event) {
gotoProfile(d.id);
}
}(dude)), false);
This is a common error when creating functions in a loop.
But you can make it even easier. The event object has a property target that points to the element the event was raised on. So you can just do:
dude.addEventListener('click', function(event) {
gotoProfile(event.target.id);
}, false);
And with that said, you don't need to add a handler for every button. As you are doing the same for every button, you could attach the same event handler above to the parent of the buttons (or a common ancestor) and it would still work. You just have to filter out the clicks that don't happen on a button:
parent.addEventListener('click', function(event) {
if(event.target.nodeName == 'INPUT' && event.target.type == "button") {
gotoProfile(event.target.id);
}
}, false);

Categories