Not able to style the suggested actions container with limited height and overflow hidden and scrollable - web-chat

I'm using these style for suggested actions. When the number of suggested actions are more, i want the suggested actions to be in a container with fixed height and overflow hidden with scrollable.
It looks like there are no style options to do the currently. Could you please check if this can done?
const styleOptions = {
suggestedActionBackground: 'White',
suggestedActionBorder: 0,
suggestedActionBorderRadius: 4,
suggestedActionBorderStyle: 'solid',
suggestedActionBorderWidth: 1,
suggestedActionHeight: 32,
suggestedActionLayout: 'stacked', // either "carousel" or "stacked"
};
enter image description here

This is achievable thru use of CSS, Web Chat's store, and an event listener. A couple things to note, however.
One, this requires manipulating the DOM directly. Generally, this is frowned upon in a React environment. Whether you are using the React version of Web Chat or not, Web Chat is built upon React. Because of this, components may change in the future which could break this setup. Please bare this in mind.
Two, the example below is a simple setup. You will need to adjust it to meet your needs. For instance, you may need to further isolate certain buttons or specific suggested actions as they arrive.
First, we setup our CSS. I have two classes. hideSuggestedActionsContainer is used to, initially, hide any suggested actions. If we don't set this immediately, then the CSS changes made to suggested actions will be momentarily visible to the user as they are rendered. suggestedActionContainer sets the container styling, including enabling (but hiding) scrolling in the container.
.hideSuggestedActionContainer {
display: none;
}
.suggestedActionContainer {
background: white;
width: 300px;
height: 200px;
display: flex;
flex-direction: column;
justify-content: flex-start;
overflow-y: scroll;
-ms-overflow-style: none;
}
.suggestedActionContainer::-webkit-scrollbar {
display: none;
}
In Web Chat, we utilize the store to manage what actions we take and when. The store is passed in as a parameter into Web Chat.
When Web Chat first connects (DIRECT_LINE/CONNECT_FULFILLED), we assign the hideSuggestedActionContainer class to the suggested actions DIV wrapper.
As the suggested action arrives (WEB_CHAT/SET_SUGGESTED_ACTIONS), we remove the hideSuggestedActionContainer class and assign the suggestedActionContainer class allowing the suggested action to be viewed.
At the same time, we monitor the incoming activities (DIRECT_LINE/INCOMING_ACTIVITY) looking for the associated HTML element that houses the suggested action. As Web Chat only allows for one suggested action to be displayed at a time, this should be the first object in the [role=status] array (again, things could change in the future). From that array, we collect the various suggested action buttons and, when one is clicked, we dispatch an event.
const store = window.WebChat.createStore( {}, ({dispatch}) => next => action => {
if ( action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
setTimeout( () => {
let actions = document.querySelectorAll( '[role=status]' );
let suggestedAction = actions[ 0 ];
suggestedAction.classList.add( 'hideSuggestedActionContainer' );
}, 20 )
}
if ( action.type === 'WEB_CHAT/SET_SUGGESTED_ACTIONS' ) {
const { suggestedActions } = action.payload;
if ( suggestedActions.length > 0 ) {
setTimeout( () => {
let actions = document.querySelectorAll( '[role=status]' );
let suggestedAction = actions[ 0 ];
suggestedAction.classList.remove('hideSuggestedActionContainer');
suggestedAction.classList.add( 'suggestedActionContainer' );
}, 20 )
}
}
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
const { activity } = action.payload;
if (activity.type === 'message') {
const actions = document.querySelectorAll( '[role=status]' );
const buttons = actions[0].querySelectorAll('button');
buttons.forEach( button => {
button.onclick = function() {
const buttonClick = new Event('buttonClick');
window.dispatchEvent( buttonClick )
};
} )
}
}
next(action);
} );
[ ... ]
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine( {
token: token
} ),
store: store,
styleOptions: styleOptions
},
document.getElementById( 'webchat' )
);
Below the Web Chat renderer, we place our event listener. As a suggested action button is clicked, we remove the suggestedActionContainer class and re-assign the hideSuggestedActionContainer class.
const buttonClickEvent = ( function () {
window.addEventListener( 'buttonClick', () => {
let actions = document.querySelectorAll( '[role=status]' );
let suggestedAction = actions[ 0 ];
suggestedAction.classList.remove( 'suggestedActionContainer' );
suggestedAction.classList.add( 'hideSuggestedActionContainer' );
} );
} )()
A note about the setTimeout() functions used in the store. The store processes every activity as it arrives before displaying it. Because of this, a slight delay needs to be applied to the changes we are pushing to the DOM. Without setTimeout(), the page tries to render our changes before the store is able to display the activity's associated HTML. I set the time outs to 20 milliseconds, but you may find you will need to adjust this. I have found that if I set the time out to too low a number then the changes occur before the activity is rendered. If it's too long (300+ ms or thereabouts), then the changes become visible to the user.
Hope of help!

Related

How to represent a state machine with HTML elements?

On a web page I wish to display an element which depends on the state of some JavaScript. State like in a state machine. Currently the possible states are these (but I may add more):
input: display some input elements for the user to set. The user can click a button to start some JavaScript processing and move to the working state.
working: display a progress bar informing the user that the script is running. The user can cancel the computation (moving back to the input state) or the computation can end (moving to either the result or error state).
result: display the computation result. The user can go back to input with a button.
error: display the error. The user can go back to input with a button.
The JavaScript part is ready and working, but I'm unsure how to do this in HTML + CSS.
Current solution and its issue
Currently I've been doing it with classes: I set a class to a common ancestor element with the same name of the state and I display the right elements based on it. Something like this:
const parent=document.querySelector("#parent");
let timer=null;
function input(){
parent.classList.remove("working","result","error");
parent.classList.add("input");
}
function run(){
parent.classList.remove("input");
parent.classList.add("working");
timer=setTimeout(result,1500)
}
function stop(){
clearTimeout(timer);
input();
}
function result(){
parent.classList.remove("working");
if(Math.random()>0.5){parent.classList.add("result");}
else{parent.classList.add("error");}
}
input();
#input{display:none;}
#working{display:none;}
#result{display:none;}
#error{display:none;}
#parent.input #input{display:block;}
#parent.working #working{display:block;}
#parent.result #result{display:block;}
#parent.error #error{display:block;}
<div id="parent">
<div id="input">INPUT. RUN</div>
<div id="working">WORKING. STOP</div>
<div id="result">RESULT. RESTART</div>
<div id="error">ERROR. RESTART</div>
</div>
This solution works but it feels unstable: in theory it would be possible for the parent element to have no classes (in which case nothing is displayed) or multiple ones (in which case you'd see multiple states at once). This shouldn't happen, but the only thing preventing it is the correctness of my script.
Question
Are there better ways to implement this idea of states, so that the HTML elements can't end up in inconsistent states?
Let’s consider the role which HTML plays in a state machine on the web. A machine has moving parts, it is dynamic, so the core of any machine on the web must be implemented in Javascript. HTML is useful only to provide the interface between the user and the machine. It’s a subtle distinction but it fundamentally changes the way you write it.
Have you ever used React? React provides the framework to create entire web applications as “state machines”. React’s mantra is “UI is a function of state”. In a React app, you have a single variable which contains the current state, rendering code which builds the UI based on the state, and core code (mostly event handlers) which updates the state.
Even if you don’t want to build in React, you can use the same general idea:
keep the current state in a Javascript variable (typically you’d use an object, but in this case we only need a string)
write a rendering function which reads the state and then builds the appropriate HTML to represent that state
in the event handlers for your links, do any operations which are required, update the state and call the rendering function
let state = null
let timer = null
// core code
const input = () => {
state = 'input'
render()
}
const run = () => {
state = 'working'
render()
timer = setTimeout(result,1500)
}
const stop = () => {
clearTimeout(timer)
state = 'input'
render()
}
const result = () => {
if(Math.random()>0.5)
state = 'result'
else
state = 'error'
render()
}
// rendering code
const render = () => {
let x = state
switch(state) {
case 'input':
x += ' run'
break
case 'working':
x += ' stop'
break
case 'result':
x += ' restart'
break
case 'error':
x += ' restart'
break
}
document.getElementById('container').innerHTML = x
}
// initialisation code
state = 'input'
render()
<div id="container"></div>

Smoothly loading messages Angular 8

I'm writing sort of a chat application using Angular 8 and here's what I want to achieve:
My dialogue component that represents a chat between two users gets one page of last messages that consists of 10 messages after initiating. The div that contains these messages scrolls down to the very last message. When a user scrolls up and reaches a certain point the next page loads. The two arrays join and the user sees now 20 messages. Here's what I have so far:
HTML:
<div>
<div #scrollMe [scrollTop]="scrollMe.scrollHeight" (scroll)="onScroll($event)" style="overflow-y: scroll; height: 400px;">
<ul>
<li *ngFor="let message of messages?.reverse()">
</ul>
</div>
</div>
Typescipt:
loadMessages(page: number, itemsPerPage?: number) {
this.messageService.getMessageThread(page, itemsPerPage || 10)
.subscribe((res: PaginatedResult<MessageThread>) => {
if (this.messages == null) {
this.messages = res.result.messages;
} else {
this.messages = this.messages.concat(res.result.messages);
}
});
}
onScroll(event) {
if (event.target.scrollTop < 100) {
if (this.pagination.currentPage >= this.pagination.totalPages) {
return;
}
this.loadMessages(++this.pagination.currentPage);
}
}
It works, but the problem is that when I join these two arrays, my scrollbar jumps very ugly and since I hold the scrollbar it stays at the same position and keeps loading next pages. I am very new to Angular and front-end in general so I have a feeling that I'm missing something. I tried to find any ready-to-go solutions but could not. Any help would be appreciated.
Please note that I don't want to use JQuery.
Several things:
First, we need a loading flag:
loading = false;
Then we make loadMessages return an observable instead of handle the result:
loadMessages(page: number, itemsPerPage?: number) {
this.loading = true;
return this.messageService.getMessageThread(page, itemsPerPage || 10);
}
A separate method handleResponse handles the response by setting loading to false and concatenating the messages.
Then we can account for the request delay in the scroll handler and use the loading flag to prevent multiple requests:
onScroll(event) {
// get the scroll height before adding new messages
const startingScrollHeight = event.target.scrollHeight;
if (event.target.scrollTop < 100) {
if (this.pagination.currentPage >= this.pagination.totalPages) {
return;
}
else if (!this.loading) {
this.loadMessages(this.pagination.currentPage).subscribe((res) => {
this.handleResponse(res);
// using setTimeout lets the app "wait a beat" so it can measure
// new scroll height *after* messages are added
setTimeout(() => {
const newScrollHeight = this.scrollDiv.nativeElement.scrollHeight;
// set the scroll height from the difference of the new and starting scroll height
this.scrollDiv.nativeElement.scrollTo(0, newScrollHeight - startingScrollHeight);
});
});
}
}
}
Stackblitz (updated)

Refresh previous screen on goBack()

I am new to React Native. How can we refresh/reload previous screen when returning to it by calling goBack()?
Lets say we have 3 screens A, B, C:
A -> B -> C
When we run goBack() from screen C it goes back to screen B but with old state/data. How can we refresh it? The constructor doesn't get called 2nd time.
Adding an Api Call in a focus callBack in the screen you're returning to solves the issue.
componentDidMount() {
this.props.fetchData();
this.willFocusSubscription = this.props.navigation.addListener(
'willFocus',
() => {
this.props.fetchData();
}
);
}
componentWillUnmount() {
this.willFocusSubscription.remove();
}
UPDATE 2023: willFocus event was renamed to focus
componentDidMount() {
this.props.fetchData();
this.focusSubscription = this.props.navigation.addListener(
'focus',
() => {
this.props.fetchData();
}
);
}
componentWillUnmount() {
this.focusSubscription();
}
How about using useIsFocused hook?
https://reactnavigation.org/docs/function-after-focusing-screen/#re-rendering-screen-with-the-useisfocused-hook
const componentB = (props) => {
// check if screen is focused
const isFocused = useIsFocused();
// listen for isFocused, if useFocused changes
// call the function that you use to mount the component.
useEffect(() => {
isFocused && updateSomeFunction()
},[isFocused]);
}
For react-navigation 5.x use
5.x
use
componentDidMount() {
this.loadData();
this.focusListener = this.props.navigation.addListener('focus', () => {
this.loadData();
//Put your Data loading function here instead of my this.loadData()
});
}
For functional component
function Home({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
loadData();
//Put your Data loading function here instead of my loadData()
});
return unsubscribe;
}, [navigation]);
return <HomeContent />;
}
On your screen B constructor will work like magic :)
this.props.navigation.addListener(
'didFocus',
payload => {
this.setState({is_updated:true});
}
);
Yes, constructor is called only for the first time and you can't call it twice.
First: But you can separate the data getter/setter from the constructor and put it in a function, this way you can pass the function down to the next Scene and whenever you're going back you may simply recall the function.
Better: You can make a go back function in your first scene which also updates the scene while going back and pass the go back function down. This way the second scene would not be aware of your update function which is reasonable.
Best: You can use redux and dispatch a go-back action in your second scene. Then in your reducer you take care of going back & refreshing your scene.
The built in listener function which comes with React-Navigation would be the easiest solution. Whenever a component is 'focused' on a again by navigating back, the listener will fire off. By writing a loadData function that can be called both when loading the Component AND when the listener is notified, you can easily reload data when navigating back.
componentWillMount(){
this._subscribe = this.props.navigation.addListener('didFocus', () => {
this.LoadData();
//Put your Data loading function here instead of my this.LoadData()
});}
Easy! insert the function inside useFocusEffect(func)
import { useFocusEffect } from '#react-navigation/native'
I have a similar situation and the way i refreshed was to reset the route when the back button is pressed. So, what happens is when the back button is pressed the screen is re-pushed into the stack and the useEffect on my screen loads the data
navigation.reset({
index: 0,
routes: [{ name: "SCREEN WHERE THE GOBACK BUTTON SHOULD GO" }],
});
Update for react-navigation v5 and use the React Hooks. Actually, the use is the same with react base class. For more detail, please checkout the documentation here
Here is the sample code:
function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
As above code, We add the event listener while the variable navigation change then We do something like call function refresh() and finally, we return the function for removing the event listener. Simple!
I think we have a very easy way (which works in 2021) to do so. Instead of using goBack or navigate, you should use push
this.props.navigation.push('your_route_B').
You can also pass params in the same way as we pass in navigate.
The only difference b/w navigate and push is that navigate checks if the route which we are passing exists in the stack. Thus taking us to the older one but, push just sends us there without checking whether that is in the stack or not (i.e, whether the route was visited earlier or not.)
This can be achived by useFocusEffect from '#react-navigation/native'
useFocusEffect will effect every time when screen is focus
Ref: https://reactnavigation.org/docs/use-focus-effect/
import { useFocusEffect } from '#react-navigation/native';
function Profile({ }) {
useFocusEffect(
React.useCallback(() => {
//Below alert will fire every time when profile screen is focused
alert('Hi from profile')
}, [])
);
return // ...code ;
}
You can use this event: navigation.addListener('focus'
And you can implement like this:
const Cards = ({ navigation }) => {
...
useEffect(() => {
const load =async ()=>{
const a = await selectGlobalCards()
}
navigation.addListener('focus',() =>{
load();
});
}, [])
or you can use useIsFocused, and you can use that as a dependecy for useEffect
import { useIsFocused } from '#react-navigation/native'
const Cards = ({ navigation }) => {
const isFocused = useIsFocused()
useEffect(() => {
const load =async ()=>{
const a = await selectGlobalCards()
}
load()
}, [isFocused])
For react navigation (5.x), you just need to add a focus subscription and put your component initializing logic in a separate function like so:
componentDidMount() {
this.init();
this.didFocusSubscription = this.props.navigation.addListener(
'focus',
() => {
this.init();
}
);
}
init = async () => {
//fetch some data and set state here
}
If you're trying to get new data into a previous view, and it isn't working, you may want to revisit the way you're piping data into that view to begin with. Calling goBack shouldn't effect the mounting of a previous component, and likely won't call its constructor again as you've noted.
As a first step, I would ask if you're using a Component, PureComponent, or Functional Component. Based on your constructor comment it sounds like you're extending a Component class.
If you're using a component, the render method is subject to shouldComponentUpdate and the value of your state is in your control.
I would recommend using componentWillReceiveProps to validate the component is receiving the new data, and ensuring its state has been updated to reflect the new data.
If you're using the constructor to call an API or async function of some kind, consider moving that function into a parent component of both the route you're calling goBack from and the component you're wanting to update with the most recent data. Then you can ask your parent component to re-query the API, or update its state from a child component.
If Route C updates the "state/data" of the application, that update should be propagated to a shared parent of routes A, B and C, and then passsed down as a prop.
Alternatively, you can use a state management solution like Redux to maintain that state independent of parent/child components - you would wrap your components in a connect higher-order component to get the latest updates any time the application state changes.
TL;DR Ultimately it sounds like the answer to your question is rooted in where your application state is being stored. It should be stored high enough in your component hierarchy that each route always receives the latest data as a prop, passed from its parent.
Thanks to #Bat.
I have spent a lot of hours on finding the answer and finally, I got a basic solution which is working according to my needs. I was quite worried though.
Simply make a function like this in your previous activity make sure to bind it.
changeData(){
var mydata= salesmanActions.retrieveAllSalesman();
this.setState({dataListFill: mydata});
alert('' + mydata.length);
}
Simple, then in constructor bind this,
this.changeData= this.changeData.bind(this);
After that, as I am using react native navigation, so I will simply pass this function to the second screen just like the code below:
onPress={() => this.props.navigation.navigate('Add Salesman', {doChange:
this.changeData} )}
So when the new screen registered as "Add Salesman" will be called, a parameter named "doChange" which is assigned a function will also be transfered to other screen.
Now, in other screen call this method anywhere, by :
this.props.route.params.doChange();
It works for me. I hope works for you too, THANKS for the idea #Bat.
let we have 2 screen A and B , screen A showing all data . and screen B is responsible for adding that data. we add some data on using screen B and want to show instant changes on Screen A . we use below code in A
componentDidMount(){
this.focusListener = this.props.navigation.addListener('focus', () => {
thi`enter code here`s.startData();
//Put your Data loading function here
});
}
This is what you can do with react navigation v6.
Create a separate stack in stack navigator like this:
const PropertyListStack = () => {
return (
<Stack.Navigator screenOptions={{headerShown: false}}>
<Stack.Screen name={ROUTE_PROPERTY_LIST} component={PropertyList}/>
</Stack.Navigator>
)};
Now, whenever you you want to reload your initial screen navigate using this stack. like this:
navigation.navigate(
ROUTE_DASHBOARD_TABS,
{screen: ROUTE_PROPERTY_LIST_STACK}
);
This will reload your base screen. In my case base screen is PropertyList.
If you know the name of the Screen you want to go , then you can use this code.
navigation.navigate("Screen"); navigation.replace("Screen");
This code works fine if you don't have nested routes.
This answer assumes that the react-native-navigation library is being used, which is unlikely because it doesn't actually have a goBack() method...
The constructor doesn't call a second time because screen A and B are still rendered (but hidden behind screen C). If you need to know when screen B is going to be visible again you can listen to navigation events.
class ScreenB extends Component {
constructor(props) {
super(props);
// Listen to all events for screen B
this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent);
}
onNavigatorEvent = event => {
switch (event.id) {
case 'willAppear':
// refresh your state...
break;
};
}
Other events: willDisappear, didAppear, didDisappear
An alternate solution to your problem is to use a state management solution like Redux to provide the state to all screens whenever it is updated (rather than just on screen transitions. See old react-native-nav/redux example.

how to force a Polymer.Element extended class to execute its lifecycle without attaching it to the dom?

Consider this element (minimal for the purpose of the question) :
class MyCountDown extends Polymer.Element
{
static get is () { return 'my-count-down'; }
static get properties ()
{
return {
time: { /* time in seconds */
type: Number,
observer: '_startCountDown'
},
remains: Number
}
}
_startCountDown ()
{
this.remains = this.time;
this.tickInterval = window.setInterval(() => {
this.remains--;
if (this.remains == 0) {
console.log('countdown!');
this._stopCountDown();
}
}, 1000);
}
_stopCountDown () {
if (this.tickInterval) {
window.clearInterval(this.tickInterval);
}
}
}
customElements.define(MyCountDown.is, MyCountDown);
If I get one instance and set the property time,
let MyCountDown = customElements.get('my-count-down');
let cd = new MyCountDown();
cd.time = 5;
the property time changes but the observer and the _startCountDown() function is not called. I believe Polymer is waiting for the Instance to be attached to the DOM because in fact when I appendChild() this element to the document the count down starts and after 5 seconds the console logs 'countdown!' as expected.
My goal is to execute this lifecycle without attaching anything to the document because the instances of MyCountDown are not always attached to the view but/and they need to be live-code between the different components of my web application.
One solution is to attach the new MyCountDown instances to an hidden element of the dom to force the Polymer lifecycle but I think this is not so intuitive.
I don't know the exact place to call, but the problem you have is that the property assessors are not in place.
I think you might get a clue from this talk https://www.youtube.com/watch?v=assSM3rlvZ8 at google i/o
call this._enableProperties() in a constructor callback?

How to detect when cancel is clicked on file input?

How can I detect when the user cancels a file input using an html file input?
onChange lets me detect when they choose a file, but I would also like to know when they cancel (close the file choose dialog without selecting anything).
While not a direct solution, and also bad in that it only (as far as I've tested) works with onfocus (requiring a pretty limiting event blocking) you can achieve it with the following:
document.body.onfocus = function(){ /*rock it*/ }
What's nice about this, is that you can attach/detach it in time with the file event, and it also seems to work fine with hidden inputs (a definite perk if you're using a visual workaround for the crappy default input type='file'). After that, you just need to figure out if the input value changed.
An example:
var godzilla = document.getElementById('godzilla')
godzilla.onclick = charge
function charge()
{
document.body.onfocus = roar
console.log('chargin')
}
function roar()
{
if(godzilla.value.length) alert('ROAR! FILES!')
else alert('*empty wheeze*')
document.body.onfocus = null
console.log('depleted')
}
See it in action: http://jsfiddle.net/Shiboe/yuK3r/6/
Sadly, it only seems to work on webkit browsers. Maybe someone else can figure out the firefox/IE solution
So I'll throw my hat into this question since I came up with a novel solution. I have a Progressive Web App which allows users to capture photos and videos and upload them. We use WebRTC when possible, but fall back to HTML5 file pickers for devices with less support *cough Safari cough*. If you're working specifically on an Android/iOS mobile web application which uses the native camera to capture photos/videos directly, then this is the best solution I have come across.
The crux of this problem is that when the page loads, the file is null, but then when the user opens the dialog and presses "Cancel", the file is still null, hence it did not "change", so no "change" event is triggered. For desktops, this isn't too bad because most desktop UI's aren't dependent on knowing when a cancel is invoked, but mobile UI's which bring up the camera to capture a photo/video are very dependent on knowing when a cancel is pressed.
I originally used the document.body.onfocus event to detect when the user returned from the file picker, and this worked for most devices, but iOS 11.3 broke it as that event is not triggered.
Concept
My solution to this is *shudder* to measure CPU timing to determine if the page is currently in the foreground or the background. On mobile devices, processing time is given to the app currently in the foreground. When a camera is visible it will steal CPU time and deprioritize the browser. All we need to do is measure how much processing time our page is given, when camera launches our available time will drop drastically. When the camera is dismissed (either cancelled or otherwise), our available time spike back up.
Implementation
We can measure CPU timing by using setTimeout() to invoke a callback in X milliseconds, and then measure how long it took to actually invoke it. The browser will never invoke it exactly after X milliseconds, but if it is reasonable close then we must be in the foreground. If the browser is very far away (over 10x slower than requested) then we must be in the background. A basic implementation of this is like so:
function waitForCameraDismiss() {
const REQUESTED_DELAY_MS = 25;
const ALLOWED_MARGIN_OF_ERROR_MS = 25;
const MAX_REASONABLE_DELAY_MS =
REQUESTED_DELAY_MS + ALLOWED_MARGIN_OF_ERROR_MS;
const MAX_TRIALS_TO_RECORD = 10;
const triggerDelays = [];
let lastTriggerTime = Date.now();
return new Promise((resolve) => {
const evtTimer = () => {
// Add the time since the last run
const now = Date.now();
triggerDelays.push(now - lastTriggerTime);
lastTriggerTime = now;
// Wait until we have enough trials before interpreting them.
if (triggerDelays.length < MAX_TRIALS_TO_RECORD) {
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
return;
}
// Only maintain the last few event delays as trials so as not
// to penalize a long time in the camera and to avoid exploding
// memory.
if (triggerDelays.length > MAX_TRIALS_TO_RECORD) {
triggerDelays.shift();
}
// Compute the average of all trials. If it is outside the
// acceptable margin of error, then the user must have the
// camera open. If it is within the margin of error, then the
// user must have dismissed the camera and returned to the page.
const averageDelay =
triggerDelays.reduce((l, r) => l + r) / triggerDelays.length
if (averageDelay < MAX_REASONABLE_DELAY_MS) {
// Beyond any reasonable doubt, the user has returned from the
// camera
resolve();
} else {
// Probably not returned from camera, run another trial.
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
}
};
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
});
}
I tested this on recent version of iOS and Android, bringing up the native camera by setting the attributes on the <input /> element.
<input type="file" accept="image/*" capture="camera" />
<input type="file" accept="video/*" capture="camcorder" />
This works out actually a lot better than I expected. It runs 10 trials by requesting a timer to be invoked in 25 milliseconds. It then measures how long it actually took to invoke, and if the average of 10 trials is less than 50 milliseconds, we assume that we must be in the foreground and the camera is gone. If it is greater than 50 milliseconds, then we must still be in the background and should continue to wait.
Some additional details
I used setTimeout() rather than setInterval() because the latter can queue multiple invocations which execute immediately after each other. This could drastically increase the noise in our data, so I stuck with setTimeout() even though it is a little more complicated to do so.
These particular numbers worked well for me, though I have see at least once instance where the camera dismiss was detected prematurely. I believe this is because the camera may be slow to open, and the device may run 10 trials before it actually becomes backgrounded. Adding more trials or waiting some 25-50 milliseconds before starting this function may be a workaround for that.
Desktop
Unfortuantely, this doesn't really work for desktop browsers. In theory the same trick is possible as they do prioritize the current page over backgrounded pages. However many desktops have enough resources to keep the page running at full speed even when backgrounded, so this strategy doesn't really work in practice.
Alternative solutions
One alternative solution not many people mention that I did explore was mocking a FileList. We start with null in the <input /> and then if the user opens the camera and cancels they come back to null, which is not a change and no event will trigger. One solution would be to assign a dummy file to the <input /> at page start, therefore setting to null would be a change which would trigger the appropriate event.
Unfortunately, there's no way official way to create a FileList, and the <input /> element requires a FileList in particular and will not accept any other value besides null. Naturally, FileList objects cannot be directly constructed, do to some old security issue which isn't even relevant anymore apparently. The only way to get ahold of one outside of an <input /> element is to utilize a hack which copy-pastes data to fake a clipboard event which can contain a FileList object (you're basically faking a drag-and-drop-a-file-on-your-website event). This is possible in Firefox, but not for iOS Safari, so it was not viable for my particular use case.
Browsers, please...
Needless to say this is patently ridiculous. The fact that web pages are given zero notification that a critical UI element has changed is simply laughable. This is really a bug in the spec, as it was never intended for a full-screen media capture UI, and not triggering the "change" event is technically to spec.
However, can browser vendors please recognize the reality of this? This could be solved with either a new "done" event which is triggered even when no change occurs, or you could just trigger "change" anyways. Yeah, that would be against spec, but it is trivial for me to dedup a change event on the JavaScript side, yet fundamentally impossible to invent my own "done" event. Even my solution is really just heuristics, if offer no guarantees on the state of the browser.
As it stands, this API is fundamentally unusable for mobile devices, and I think a relatively simple browser change could make this infinitely easier for web developers *steps off soap box*.
You can't.
The result of the file dialog is not exposed to the browser.
When you select a file and click open/cancel, the input element should lose focus aka blur. Assuming the initial value of the input is empty, any non empty value in your blur handler would indicate an OK, and an empty value would mean a Cancel.
UPDATE: The blur is not triggered when the input is hidden. So can't use this trick with IFRAME-based uploads, unless you want to temporarily display the input.
Most of these solutions don't work for me.
The problem is that you never know which event will be triggered fist,
is it click or is it change? You can't assume any order, because it probably depends on the browser's implementation.
At least in Opera and Chrome (late 2015) click is triggered just before 'filling' input with files, so you will never know the length of files.length != 0 until you delay click to be triggered after change.
Here is code:
var inputfile = $("#yourid");
inputfile.on("change click", function(ev){
if (ev.originalEvent != null){
console.log("OK clicked");
}
document.body.onfocus = function(){
document.body.onfocus = null;
setTimeout(function(){
if (inputfile.val().length === 0) console.log("Cancel clicked");
}, 1000);
};
});
/* Tested on Google Chrome */
$("input[type=file]").bind("change", function() {
var selected_file_name = $(this).val();
if ( selected_file_name.length > 0 ) {
/* Some file selected */
}
else {
/* No file selected or cancel/close
dialog button clicked */
/* If user has select a file before,
when they submit, it will treated as
no file selected */
}
});
The new File System Access API will make our life easy again :)
try {
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
// ...
}
catch (e) {
console.log('Cancelled, no file selected');
}
Browser support is very limited (Jan, 2021). The example code works well in Chrome Desktop 86.
Just listen to the click event as well.
Following from Shiboe's example, here's a jQuery example:
var godzilla = $('#godzilla');
var godzillaBtn = $('#godzilla-btn');
godzillaBtn.on('click', function(){
godzilla.trigger('click');
});
godzilla.on('change click', function(){
if (godzilla.val() != '') {
$('#state').html('You have chosen a Mech!');
} else {
$('#state').html('Choose your Mech!');
}
});
You can see it in action here: http://jsfiddle.net/T3Vwz
You can catch the cancel if you choose the same file as previously and you click cancel: in this case.
You can do it like this:
<input type="file" id="myinputfile"/>
<script>
document.getElementById('myinputfile').addEventListener('change', myMethod, false);
function myMethod(evt) {
var files = evt.target.files;
f= files[0];
if (f==undefined) {
// the user has clicked on cancel
}
else if (f.name.match(".*\.jpg")|| f.name.match(".*\.png")) {
//.... the user has choosen an image file
var reader = new FileReader();
reader.onload = function(evt) {
try {
myimage.src=evt.target.result;
...
} catch (err) {
...
}
};
}
reader.readAsDataURL(f);
</script>
The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it.
var yourFileInput = $("#yourFileInput");
yourFileInput.on('mouseup', function() {
$(this).trigger("change");
}).on('change', function() {
if (this.files.length) {
//User chose a picture
} else {
//User clicked cancel
}
});
In my case i had to hide submit button while users were selecting images.
This is what i come up:
$(document).on('click', '#image-field', function(e) {
$('.submit-button').prop('disabled', true)
})
$(document).on('focus', '#image-field'), function(e) {
$('.submit-button').prop('disabled', false)
})
#image-field is my file selector. When somenone clicks on it, i disable the form submit button. The point is, when the file dialog closed - doesn't matter they select a file or cancel - #image-field got the focus back, so i listen on that event.
UPDATE
I found that, this does not work in safari and poltergeist/phantomjs. Take this info into account if you would like to implement it.
Shiboe's solution would be a good one if it worked on mobile webkit, but it doesn't. What I can come up with is to add a mousemove event listener to some dom object at the time that the file input window is opened, like so:
$('.upload-progress').mousemove(function() {
checkForFiles(this);
});
checkForFiles = function(me) {
var filefield = $('#myfileinput');
var files = filefield.get(0).files;
if (files == undefined || files[0] == undefined) $(me).remove(); // user cancelled the upload
};
The mousemove event is blocked from the page while the file dialog is open, and when its closed one checks to see if there are any files in the file input. In my case I want an activity indicator blocking things till the file is uploaded, so I only want to remove my indicator on cancel.
However this doesn't solve for mobile, since there is no mouse to move. My solution there is less than perfect, but I think its good enough.
$('.upload-progress').bind('touchstart', function() {
checkForFiles(this);
});
Now we're listening for a touch on the screen to do the same files check. I'm pretty confident that the user's finger will be put on the screen pretty quickly after cancel and dismiss this activity indicator.
One could also just add the activity indicator on the file input change event, but on mobile there is often a few seconds lag between selecting the image and the change event firing, so its just much better UX for the activity indicator to be displayed at the start of the process.
I found this atribute, its most simple yet.
if ($('#selectedFile')[0].files.length > 1)
{
// Clicked on 'open' with file
} else {
// Clicked on 'cancel'
}
Here, selectedFile is an input type=file.
I know this is a very old question but just in case it helps someone, I found when using the onmousemove event to detect the cancel, that it was necessary to test for two or more such events in a short space of time.
This was because single onmousemove events are generated by the browser (Chrome 65) each time the cursor is moved out of the select file dialog window and each time it is moved out of the main window and back in.
A simple counter of mouse movement events coupled with a short duration timeout to reset the counter back to zero worked a treat.
Combining Shiboe's and alx's solutions, i've got the most reliable code:
var selector = $('<input/>')
.attr({ /* just for example, use your own attributes */
"id": "FilesSelector",
"name": "File",
"type": "file",
"contentEditable": "false" /* if you "click" on input via label, this prevents IE7-8 from just setting caret into file input's text filed*/
})
.on("click.filesSelector", function () {
/* do some magic here, e.g. invoke callback for selection begin */
var cancelled = false; /* need this because .one calls handler once for each event type */
setTimeout(function () {
$(document).one("mousemove.filesSelector focusin.filesSelector", function () {
/* namespace is optional */
if (selector.val().length === 0 && !cancelled) {
cancelled = true; /* prevent double cancel */
/* that's the point of cancel, */
}
});
}, 1); /* 1 is enough as we just need to delay until first available tick */
})
.on("change.filesSelector", function () {
/* do some magic here, e.g. invoke callback for successful selection */
})
.appendTo(yourHolder).end(); /* just for example */
Generally, mousemove event does the trick, but in case user made a click and than:
cancelled file open dialog by escape key (without moving a mouse), made another accurate click to open file dialog again...
switched focus to any other application, than came back to browser's file open dialog and closed it, than opened again via enter or space key...
... we won't get mousemove event hence no cancel callback. Moreover, if user cancels second dialog and makes a mouse move, we'll get 2 cancel callbacks.
Fortunately, special jQuery focusIn event bubbles up to the document in both cases, helping us to avoid such situations. The only limitation is if one blocks focusIn event either.
I see that my response would be quite outdated, but never the less.
I faced with the same problem. So here's my solution.
The most useful code snipped was KGA's one. But it isn't totally working and is a bit complicated. But I simplified it.
Also, the main trouble maker was that fact, that 'change' event doesn't come instantly after focus, so we have to wait for some time.
"#appendfile" - which user clicks on to append a new file.
Hrefs get focus events.
$("#appendfile").one("focusin", function () {
// no matter - user uploaded file or canceled,
// appendfile gets focus
// change doesn't come instantly after focus, so we have to wait for some time
// wrapper represents an element where a new file input is placed into
setTimeout(function(){
if (wrapper.find("input.fileinput").val() != "") {
// user has uploaded some file
// add your logic for new file here
}
else {
// user canceled file upload
// you have to remove a fileinput element from DOM
}
}, 900);
});
You can detect this only in limited circumstances. Specifically, in chrome if a file was selected earlier and then the file dialog is clicked and cancel clicked, Chrome clears the file and fires the onChange event.
https://code.google.com/p/chromium/issues/detail?id=2508
In this scenario, you can detect this by handling the onChange event and checking the files property.
This is hacky at best, but here is a working example of my solution to detect whether or not a user has uploaded a file, and only allowing them to proceed if they have uploaded a file.
Basically hide the Continue, Save, Proceed or whatever your button is. Then in the JavaScript you grab the file name. If the file name does not have a value, then do not show the Continue button. If it does have a value, then show the button. This also works if they at first upload a file and then they try to upload a different file and click cancel.
Here is the code.
HTML:
<div class="container">
<div class="row">
<input class="file-input" type="file" accept="image/*" name="fileUpload" id="fileUpload" capture="camera">
<label for="fileUpload" id="file-upload-btn">Capture or Upload Photo</label>
</div>
<div class="row padding-top-two-em">
<input class="btn btn-success hidden" id="accept-btn" type="submit" value="Accept & Continue"/>
<button class="btn btn-danger">Back</button>
</div></div>
JavaScript:
$('#fileUpload').change(function () {
var fileName = $('#fileUpload').val();
if (fileName != "") {
$('#file-upload-btn').html(fileName);
$('#accept-btn').removeClass('hidden').addClass('show');
} else {
$('#file-upload-btn').html("Upload File");
$('#accept-btn').addClass('hidden');
}
});
CSS:
.file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.file-input + label {
font-size: 1.25em;
font-weight: normal;
color: white;
background-color: blue;
display: inline-block;
padding: 5px;
}
.file-input:focus + label,
.file-input + label:hover {
background-color: red;
}
.file-input + label {
cursor: pointer;
}
.file-input + label * {
pointer-events: none;
}
For the CSS a lot of this is to make the website and button accessible for everyone. Style your button to whatever you like.
The following seems to work for me (on desktop, windows):
var openFile = function (mimeType, fileExtension) {
var defer = $q.defer();
var uploadInput = document.createElement("input");
uploadInput.type = 'file';
uploadInput.accept = '.' + fileExtension + ',' + mimeType;
var hasActivated = false;
var hasChangedBeenCalled = false;
var hasFocusBeenCalled = false;
var focusCallback = function () {
if (hasActivated) {
hasFocusBeenCalled = true;
document.removeEventListener('focus', focusCallback, true);
setTimeout(function () {
if (!hasChangedBeenCalled) {
uploadInput.removeEventListener('change', changedCallback, true);
defer.resolve(null);
}
}, 300);
}
};
var changedCallback = function () {
uploadInput.removeEventListener('change', changedCallback, true);
if (!hasFocusBeenCalled) {
document.removeEventListener('focus', focusCallback, true);
}
hasChangedBeenCalled = true;
if (uploadInput.files.length === 1) {
//File picked
var reader = new FileReader();
reader.onload = function (e) {
defer.resolve(e.target.result);
};
reader.readAsText(uploadInput.files[0]);
}
else {
defer.resolve(null);
}
};
document.addEventListener('focus', focusCallback, true); //Detect cancel
uploadInput.addEventListener('change', changedCallback, true); //Detect when a file is picked
uploadInput.click();
hasActivated = true;
return defer.promise;
}
This does use angularjs $q but you should be able to replace it with any other promise framework if needed.
Tested on IE11, Edge, Chrome, Firefox, but it does not seem to work on Chrome on a Android Tablet as it does not fire the Focus event.
The file-type field, frustratingly, doesn't respond to a lot of events (blur would be lovely). I see a lot of people suggesting change-oriented solutions and them getting downvoted.
change does work, but it has a major flaw (vs what we want to happen).
When you freshly load a page containing a file field, open the box and press cancel. Nothing, frustratingly, changes.
What I chose to do is load in a gated-state.
The next part of the form a section#after-image in my case is hidden from view. When my file field changes, an upload button is shown. Upon successful upload, section#after-image is shown.
If the user loads, opens the file-dialog, then cancels out, they never see the upload button.
If the user chooses a file, the upload button is shown. If they then open the dialog and cancel, the change event is triggered by this cancel, and there I can (and do) re-hide my upload button until a proper file is selected.
I was fortunate that this gated-state was already the design of my form. You do not need to use the same style, merely having the upload button initially hidden and upon change, setting a hidden field or javascript variable to something you can monitor on submit.
I tried changing the value of files[0] before the field was interacted with. This didn't do anything regarding onchange.
So yes, change works, at least as good as we're going to get. The filefield is secured, for obvious reasons, but to the frustration of well-intentioned developers.
It's not fitting to my purpose, but you might be able to, onclick, load a warning prompt (not an alert(), because that stalls page-processing), and hide it if change is triggered and files[0] is null. If change is not triggered, the div remains in its state.
Solution for file selection with hidden input
Note: this code doesn't detect cancellation, it offers a way to circumvent the need to detect it in a common case in which people try to detect it.
I got here while looking for a solution for file uploads using a hidden input, I believe that this is the most common reason to look for a way to detect cancellation of file input (open file dialog -> if a file was selected then run some code, otherwise do nothing), here's my solution:
var fileSelectorResolve;
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.addEventListener('input', function(){
fileSelectorResolve(this.files[0]);
fileSelectorResolve = null;
fileSelector.value = '';
});
function selectFile(){
if(fileSelectorResolve){
fileSelectorResolve();
fileSelectorResolve = null;
}
return new Promise(function(resolve){
fileSelectorResolve = resolve;
fileSelector.dispatchEvent(new MouseEvent('click'));
});
}
Usage example:
Note that if no file was selected then the first line will return only once selectFile() is called again (or if you called fileSelectorResolve() from elsewhere).
async function logFileName(){
const file = await selectFile();
if(!file) return;
console.log(file.name);
}
Another example:
async function uploadFile(){
const file = await selectFile();
if(!file) return;
// ... make an ajax call here to upload the file ...
}
There is a hackish way to do this (add callbacks or resolve some deferred/promise implementation instead of alert() calls):
var result = null;
$('<input type="file" />')
.on('change', function () {
result = this.files[0];
alert('selected!');
})
.click();
setTimeout(function () {
$(document).one('mousemove', function () {
if (!result) {
alert('cancelled');
}
});
}, 1000);
How it works: while file selection dialog is open, document does not receive mouse pointer events. There is 1000ms delay to allow the dialog to actually appear and block browser window. Checked in Chrome and Firefox (Windows only).
But this is not a reliable way to detect cancelled dialog, of course. Though, might improve some UI behavior for you.
Here is my solution, using the file input focus (not using any timers)
var fileInputSelectionInitiated = false;
function fileInputAnimationStart() {
fileInputSelectionInitiated = true;
if (!$("#image-selector-area-icon").hasClass("fa-spin"))
$("#image-selector-area-icon").addClass("fa-spin");
if (!$("#image-selector-button-icon").hasClass("fa-spin"))
$("#image-selector-button-icon").addClass("fa-spin");
}
function fileInputAnimationStop() {
fileInputSelectionInitiated = false;
if ($("#image-selector-area-icon").hasClass("fa-spin"))
$("#image-selector-area-icon").removeClass("fa-spin");
if ($("#image-selector-button-icon").hasClass("fa-spin"))
$("#image-selector-button-icon").removeClass("fa-spin");
}
$("#image-selector-area-wrapper").click(function (e) {
$("#fileinput").focus();
$("#fileinput").click();
});
$("#preview-image-wrapper").click(function (e) {
$("#fileinput").focus();
$("#fileinput").click();
});
$("#fileinput").click(function (e) {
fileInputAnimationStart();
});
$("#fileinput").focus(function (e) {
fileInputAnimationStop();
});
$("#fileinput").change(function(e) {
// ...
}
Well, this doesn't exactly answers your question. My assumption is that, you have a scenario, when you add a file input, and invoke file selection, and if user hits cancel, you just remove the input.
If this is the case, then: Why adding empty file input?
Create the one on the fly, but add it to DOM only when it is filled in. Like so:
var fileInput = $("<input type='file' name='files' style='display: none' />");
fileInput.bind("change", function() {
if (fileInput.val() !== null) {
// if has value add it to DOM
$("#files").append(fileInput);
}
}).click();
So here I create <input type="file" /> on the fly, bind to it's change event and then immediately invoke click. On change will fire only when user selects a file and hits Ok, otherwise input will not be added to DOM, therefore will not be submitted.
Working example here: https://jsfiddle.net/69g0Lxno/3/
//Use hover instead of blur
var fileInput = $("#fileInput");
if (fileInput.is(":hover") {
//open
} else {
}
function file_click() {
document.body.onfocus = () => {
setTimeout(_=>{
let file_input = document.getElementById('file_input');
if (!file_input.value) alert('please choose file ')
else alert(file_input.value)
document.body.onfocus = null
},100)
}
}
Using setTimeout to get the certain value of the input.
If you already require JQuery, this solution might do the work (this is the exact same code I actually needed in my case, although using a Promise is just to force the code to wait until file selection has been resolved):
await new Promise(resolve => {
const input = $("<input type='file'/>");
input.on('change', function() {
resolve($(this).val());
});
$('body').one('focus', '*', e => {
resolve(null);
e.stopPropagation();
});
input.click();
});
There are several proposed solutions in this thread and this difficulty to detecting when the user clicks the "Cancel" button on the file selection box is a problem that affects many people.
The fact is that there is no 100% reliable way to detect if the user has clicked the "Cancel" button on the file selection box. But there are ways to reliably detect if the user has added a file to the input file. So this is the basic strategy of this answer!
I decided to add this answer because apparently the other answers don't work on most browsers or guaranteed on mobile devices.
Briefly the code is based on 3 points:
The input file is initially created dynamically in "memory" in js
(we don't add it to the "HTML" at this moment);
After adding the file then the input file is added to the HTML, otherwise nothing occurs;
The removal of the file is done by removing the input file from the
HTML by a specific event, which means that the
"editing"/"modification" of the file is done by removing the old
input file and creating a new one.
For a better understanding look at the code below and the notes as well.
[...]
<button type="button" onclick="addIptFl();">ADD INPUT FILE!</button>
<span id="ipt_fl_parent"></span>
[...]
function dynIptFl(jqElInst, funcsObj) {
if (typeof funcsObj === "undefined" || funcsObj === "") {
funcsObj = {};
}
if (funcsObj.hasOwnProperty("before")) {
if (!funcsObj["before"].hasOwnProperty("args")) {
funcsObj["before"]["args"] = [];
}
funcsObj["before"]["func"].apply(this, funcsObj["before"]["args"]);
}
var jqElInstFl = jqElInst.find("input[type=file]");
// NOTE: Open the file selection box via js. By Questor
jqElInstFl.trigger("click");
// NOTE: This event is triggered if the user selects a file. By Questor
jqElInstFl.on("change", {funcsObj: funcsObj}, function(e) {
// NOTE: With the strategy below we avoid problems with other unwanted events
// that may be associated with the DOM element. By Questor
e.preventDefault();
var funcsObj = e.data.funcsObj;
if (funcsObj.hasOwnProperty("after")) {
if (!funcsObj["after"].hasOwnProperty("args")) {
funcsObj["after"]["args"] = [];
}
funcsObj["after"]["func"].apply(this, funcsObj["after"]["args"]);
}
});
}
function remIptFl() {
// NOTE: Remove the input file. By Questor
$("#ipt_fl_parent").empty();
}
function addIptFl() {
function addBefore(someArgs0, someArgs1) {
// NOTE: All the logic here happens just before the file selection box opens.
// By Questor
// SOME CODE HERE!
}
function addAfter(someArgs0, someArgs1) {
// NOTE: All the logic here happens only if the user adds a file. By Questor
// SOME CODE HERE!
$("#ipt_fl_parent").prepend(jqElInst);
}
// NOTE: The input file is hidden as all manipulation must be done via js.
// By Questor
var jqElInst = $('\
<span>\
<button type="button" onclick="remIptFl();">REMOVE INPUT FILE!</button>\
<input type="file" name="input_fl_nm" style="display: block;">\
</span>\
');
var funcsObj = {
before: {
func: addBefore,
args: [someArgs0, someArgs1]
},
after: {
func: addAfter,
// NOTE: The instance with the input file ("jqElInst") could be passed
// here instead of using the context of the "addIptFl()" function. That
// way "addBefore()" and "addAfter()" will not need to be inside "addIptFl()",
// for example. By Questor
args: [someArgs0, someArgs1]
}
};
dynIptFl(jqElInst, funcsObj);
}
Thanks! =D
We achieved in angular like below.
bind click event on input type file.
Attach focus event with window and add condition if uploadPanel is true then show console.
when click on input type file the boolean uploadPanel value is true. and dialogue box appear.
when cancel OR Esc button click then dialogue box dispensary and console appear.
HTML
<input type="file" formControlName="FileUpload" click)="handleFileInput($event.target.files)" />
/>
TS
this.uploadPanel = false;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
console.log("ggg" + files);
this.uploadPanel = true;
}
#HostListener("window:focus", ["$event"])
onFocus(event: FocusEvent): void {
if (this.uploadPanel == true) {
console.log("cancel clicked")
this.addSlot
.get("FileUpload")
.setValidators([
Validators.required,
FileValidator.validate,
requiredFileType("png")
]);
this.addSlot.get("FileUpload").updateValueAndValidity();
}
}
Just add 'change' listener on your input whose type is file. i.e
<input type="file" id="file_to_upload" name="file_to_upload" />
I have done using jQuery and obviously anyone can use valina JS (as per the requirement).
$("#file_to_upload").change(function() {
if (this.files.length) {
alert('file choosen');
} else {
alert('file NOT choosen');
}
});