Type Script BeforeUnloadEvent not firing - javascript

In my application I have an comment box where I would like to display a message that it was not saved. In the function warnOpenEditor I have added window.onbeforeunload event but it will not fire. Attached TS and html file.
Is there anything else I need to do for this event to fire?
TS file
import
#HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
if (this.IsTouched = true) {
event.returnValue = 'You have unfinished changes!';
}
}
private cancel() {
this.IsTouched = false;
if (this.comments.length === 0) {
this.hideComments();
} else {this.hideEditor();}
this.commentText = "";}
private warnOpenEditor() {
this.IsTouched = true;
for (let i = 0; i < 2; i++) {
this.$commentForm.fadeTo(100, 0.3).fadeTo(100, 1.0);}
}
}
SideCommentsComponet.html
<p class="comment" [innerHTML]="comment.Content | newline">

Did you try to move unload event out of method?
You should use this code
#HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
//check your comment box value to show message
}

Related

Keep focus inside the modal while open

I want to keep the focus inside the modal with its respective focusable elements, I'm working with "WEB COMPONENTS, DOW AND SHADOW DOW"
when trying to perform this code snippet, focus still continues to show error and go to elements outside the modal
private setFocus(): void {
const focusableElements = this.querySelectorAll('a[href], button, details, input, select, textarea, [tabindex]:not([tabindex="-1"]), ani-button, ani-textfield');
const firstFocusableElement = focusableElements[0];
const lastFocusableElement = focusableElements[focusableElements.length - 1];
this.addEventListener('keydown', event => {
const isTabbed = event.key === 'Tab' || event.code === '9';
if (!isTabbed) {
return;
}
if (event.shiftKey) {
if (document.activeElement === firstFocusableElement) {
(lastFocusableElement as HTMLElement).focus();
event.preventDefault();
}
} else {
if (document.activeElement === lastFocusableElement) {
(firstFocusableElement as HTMLElement).focus();
event.preventDefault();
}
}
});
(firstFocusableElement as HTMLElement).focus();
}
open(): void {
// this.hidden = false;
this.setAttribute('visible', 'true');
this.setFocus();
}

Focus on inputfield after DOM is loaded with Blazor

I want that my inputfield is focused when when I open the Website, it always focus the Link when I start it.
Secondly I have to Sacn muliple numbers into my inputfield with a Scanner. It triggers my function addToTable. So my number will be added to a list. after that It should clear the inputfield and focus on it again, so I can scan in the next number:
<input id="LeNumber" name="LeNumber" #onkeydown="addToTable" #onclick:preventDefault="#isPreventDefault"/>
private async void addToTable(KeyboardEventArgs args)
{
if (args.Key != "Tab")
{
LeNumber += args.Key.ToString();
}
else
{
if (!string.IsNullOrWhiteSpace(LeNumber))
{
if (todos.Contains(LeNumber))
{
LeNumber = null;
await SetValueBack("LeNumber");
await TurnRed("table");
await Focus("LeNumber");
}
else
{
if (LeNumber == "submit")
{
generateXml();
b += 1;
}
else
{
todos.Add(LeNumber);
LeNumber = null;
await SetValueBack("LeNumber");
await TurnNormal("table");
await Focus("LeNumber");
}
}
}
}
}
The Problem now is that it doesn't set the focus back on my inputfield. To set my Focus I have a JS Function witch do: document.getElementByID(id).focus().
That doesn't work but it works if I put a delay in like the following:
function focusElement(id) {
setTimeout(function () {
document.getElementById(id).focus();
}, 3000);
}
I Think it doesnt work because the focus gets lost when it displays the List:
#{
for (int i = 0; i < todos.Count; i++)
{
if (i % 2 == 0)
{
#:<tr>
<td>#todos[i]</td>
}
else
{
<td>#todos[i]</td>
#:</tr>
}
}
}
Is there a way to set the focus after everything is done? Because It would be very "ugly" to do this with the delay
Blazor has a method for this. FocusAsync().
I believe if you call it in the OnAfterRender handler, or in your event handlers, you will achieve what you want.
https://www.youtube.com/watch?v=lLypM7oBwyA

How to trigger popup when browser tab closes in ReactJS?

I have a enrollment form with some customer related information. If user form is half filled and the user is going to close the tab, then I'll trigger the popup with option of save and exit, exit.
I have some jQuery solution. But nowadays it's not working in all browsers.
Jquery sample Code:
'use strict';
$(document).ready(function() {
$.fn.addEvent = function (obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on'+evType, fn);
return r;
} else {
return false;
}
};
$.fn.KeepOnPage = function (e) {
var doWarn = 1;
if (!e) {
e = window.event;
}
if (!e) {
return;
}
if (doWarn == 1) { // and condition whatever you want to add here
e.cancelBubble = true;
e.returnValue = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
}
if (e.stopPropagation) {
e.stopPropagation();
}
};
$.fn.addEvent(window, 'beforeunload', $.fn.KeepOnPage);
});
But we need solution in ReactJS. Is there any React library for the browser unload?
Thanks,
Thangadurai
You can add and remove an event listener for the 'beforeunload' event within your componentDidMount and componentWillUnmount lifecycle functions.
https://facebook.github.io/react/docs/component-specs.html
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Example:
...
componentDidMount() {
window.addEventListener('beforeunload', this.keepOnPage);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.keepOnPage);
}
keepOnPage(e) {
var message = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
e.returnValue = message;
return message;
}
....

Javascript seems not working to load image when page loads

I'm using Javascript to make my checkboxes larger. Doing this I use image one for black checkbox and another one with the checked checkbox. It works like the real checkbox. However, when the page loads, the black checkboxes are not successfully loaded unless I click somewhere in the page to invoke them. Please check here to the page.
Belowing is my js code which I think it will impact this:
var Custom = {
init: function() {
var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
for(a = 0; a < inputs.length; a++) {
if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
span[a] = document.createElement("span");
span[a].className = inputs[a].type;
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
} else {
span[a].style.background = unchecked;
}
}
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
inputs[a].onchange = Custom.clear;
if(!inputs[a].getAttribute("disabled")) {
span[a].onmousedown = Custom.pushed;
span[a].onmouseup = Custom.check;
} else {
span[a].className = span[a].className += " disabled";
}
}
}
}
Below is my image on form load:
And this is my page when clicking on anywhere:
Which other functions and variables are already defined. Thus could anyone help me to enable them to display whenever the form loads?
I don't known why you use that
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
} else {
span[a].style.background = unchecked;
}
}
But when I open your script in http://checkintonight.freeiz.com/js/custom-form-elements.js
Try to call function clear() in end of Custom.init(), it works
init: function() {
//
...
//
this.clear();
}
Sorry for my bad English
Eventually, I found a bug in my Javascript code. I add the else statement in the init() function to test if the checkbox is also not checked. So the code becomes like below:
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
}
} else {
span[a].style.background = unchecked;
}
Then it works! Thanks everyone that reviewed and answered to my question.

Alternative to Mozilla 'explicitOriginalTarget' for cross browser functionality

I have a fiddle at: http://jsfiddle.net/radi8/Nt556/1/
This class will bind a listener to all of the 'submit' buttons on a form. When the user clicks on one of the buttons, the class function will process it as necessary. I originally developed this class using FireFox and using the: var btnName = event.originalEvent.explicitOriginalTarget.defaultValue; works great therein, but I later found that this is a Mozilla only function.
Can anyone offer an alternative for IE and Chrome?
my class:
var RequiredField = {
init: function() {
var theForm = document.getElementsByTagName("form");
$(theForm).bind("submit", RequiredField.submitListener);
},
submitListener: function(event) {
event.preventDefault();
var btnName = event.originalEvent.explicitOriginalTarget.defaultValue;
if (btnName == 'Process Route') {
processType = 0;
alert('Process');
}
else if (btnName == 'Finalize Route') {
processType = 1;
alert('Finalize');
}
else {
processType = 99;
}
try {
}
catch (e) {
event.preventDefault();
}
}
};
RequiredField.init();
I'd just bind "click" for the form:
$('form').delegate(':submit', 'click', RequiredField.submitListener);
Then the target of the event will be the button directly.

Categories