How can I determine if a file input has been clicked? - javascript

I have a script that will trigger the click event for a file upload form. I want to be able to determine of the file upload button has already been clicked. Here is what I have:
<div ng-click="uploadFile()">Click Me</div>
<input name="uploader" type="file" style="display:none;">
var uploadFile = function () {
var interval = setInterval(function () {
$('input[name=uploader]').trigger('click');
clearInterval(interval);
}, 50);
}
The problem is that the upload button is triggered twice. The first time the file browser opens up, allowing me to select a local file to upload. But, if I hit cancel, the file browser opens back up again. I would like to place a condition in the above code that would check to see if the file upload button has already been triggered. How can I do this? Something like the following:
var interval = setInterval(function () {
if(hasUploaderBeenTriggered === false) { // not sure how to do this part
$('input[name=uploader]').trigger('click');
clearInterval(interval);
}
}, 50);

Do you really need the first click or do you just want to know when the user selected their file? Otherwise you could check out onchange instead of onclick.
You can create a global variable / boolean that you switch on and off when the user clicks the button, if the user then clicks the button again you can check if the boolean is false.
Put var hasUploaderBeenTriggered = false; at the very top of your javascript and then add hasUploaderBeenTriggered = true; after clearInterval(interval); like so:
var hasUploaderBeenTriggered = false;
var interval = setInterval(function () {
if(hasUploaderBeenTriggered === false) { // not sure how to do this part
$('input[name=uploader]').trigger('click');
clearInterval(interval);
hasUploaderBeenTriggered = true;
}
}, 50);

Related

How to prevent onbeforeunload from running in pure javascript?

I had used window.onbeforeunload = function() when the user was trying to refresh the page by mistake and now I would like to cancel the loading of the page when he clicks on an icon?
Here is what I had tried, but it did not work.
crossremove.onclick = () => {
/**
* To prevent that the page does not refresh any more seen
* that one removed the file in the input. We have to do this.
*/
window.onbeforeunload = null;
// REMOVE THE FILE IN THE FIELD INPUT
inputFile.value = ""
// HIDE THE ERROR OF THE FILE UPLOADED BY MISTAKE.
fileUpload.style.display = 'none'
// REMOVE THE TITLE OF THE IMAGE ERROR THAT WAS DISPLAYED
fileNameLabel.textContent = ''
// RESHOW THE INPUT OF UPLOAD FILE.
labelUplbl.style.display = null
}
What could you suggest I do, please?
Here is what I had to do first.
inputFile.addEventListener("change", function(){
/**
* Getting user select file and [0] this means if user
* select multiple files then we'll select only the first one
*/
file = this.files[0]
setInterval(function(){
var checkIfFileExist = file.name
if ( checkIfFileExist != '' ) {
window.onbeforeunload = function() {
return true
}
}
}, 1000)
dropArea.classList.add("active")
showFile() //calling function
})

beforeinstallprompt triggers on every load

Beforeinstallprompt triggers on every load.
I have used the code here: https://developers.google.com/web/fundamentals/app-install-banners/
I am not using the The mini-info bar which i have dissabled by calling e.preventDefault();
The problem is that the showAddToHomeScreen(); is called on every load if the user does not click addToHomeScreen.
I want the showAddToHomeScreen(); function to be called only every month or so by storing information about the last "canceled" click in sessions or something similar. Isn't google suppose to do this on it's own?
This i found on the following link:
https://developers.google.com/web/updates/2018/06/a2hs-updates
You can only call prompt() on the deferred event once, if the user clicks cancel on the dialog, you'll need to wait until the beforeinstallprompt event is fired on the next page navigation. Unlike traditional permission requests, clicking cancel will not block future calls to prompt() because it call must be called within a user gesture.
window.addEventListener('beforeinstallprompt', function (e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
showAddToHomeScreen();
});
function showAddToHomeScreen() {
var prompt = document.querySelector(".a2hs-prompt");
prompt.style.display = "flex";
var open = document.querySelector(".a2hsBtn");
open.addEventListener("click", addToHomeScreen);
var close = document.querySelector(".a2hsBtn-close");
close.addEventListener("click", function() {
prompt.style.display = "none";
});
}
function addToHomeScreen() {
var prompt = document.querySelector(".a2hs-prompt");
// hide our user interface that shows our A2HS button
prompt.style.display = 'none';
if (deferredPrompt) {
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then(
function (choiceResult) {
if (choiceResult.outcome === 'accepted') {
show_ad2hs_success_message();
}
deferredPrompt = null;
});
}
}
You have to define your own session and add expire date. This is simple with ajax. This is how i did:
Javascript:
$(document).ready(function() {
$.ajax({
url: '/update_session_addtohomescreen',
success: function (session_expired) {
if(session_expired=='True'){
showAddToHomeScreen();
}
},
error: function () {
alert("it didn't work");
}
});
});
This is wrapping the showAddToHomeScreen(); function
View
#csrf_exempt
def update_session_addtohomescreen(request):
if request.is_ajax():
number_of_days_till_expire = 1
now_in_secs = time.time()
if not 'last_session_coockie' in request.session or now_in_secs > request.session['last_session_coockie']+60:#number_of_days_till_expire*86400:
session_expired = True
request.session['last_session_coockie'] = now_in_secs
else:
session_expired = False
return HttpResponse(session_expired)
return None
You should though include csrf token in your request and also add the url to urls.py

Make an onclick event react different when click second time

I have a button on my website, which plays the music when you click on it and in the same time it changes the text inside of the button (to "Go to SoundCloud".)
I want that button (with the new text on it) to redirect to SoundCloud when I click on it.
Now I got both when click first time, which is redirect to SoundCloud and play the track. (plus it changes the text)
Any ideas, how to solve this problem? Thx!
var links = document.getElementById("playButton");
links.onclick = function() {
var html='<iframe width="100%" height="450" src="sourceOfMyMusic"></iframe>';
document.getElementById("soundCloud").innerHTML = html;
var newTexts = ["Go to SoundCloud"];
document.getElementById("playButton").innerHTML = newTexts;
newTexts.onclick = window.open('http://soundcloud.com/example');
};
Use a variable that indicates whether it's the first or second click.
var first_click = true;
links.onclick = function() {
if (first_click) {
// do stuff for first click
first_click = false;
} else {
// do stuff for second click
}
}
Just redefine the onclick after the first function call.
Put the onclick on the button instead of the html.
document.getElementById("playButton").onclick=window.open('http://soundcloud.com/example');
Another option in some cases is to use a ternary operator and a boolean toggle expression:
let btn = document.querySelector('.button');
let isToggledOn = false;
btn.addEventListener ('click', function(e) {
e.target.textContent = !isToggledOn ? 'Is ON' : 'Is OFF';
isToggledOn = !isToggledOn;
});
newTexts.onclick is not creating a function to open a window, it is simply taking the return value of window.open which is being executed right away.
It should look like:
newTexts.onclick = () => window.open('http://soundcloud.com/example');
Also this will not work as intended because newTexts is not the actual DOM element, you need to attach the new onclick on the element and not the array...
But to other answers in this page, the logic is hard to read, so I'd advise to refactor the logic to be more readable.

Commit settings instantly Windows 8 app

I'm trying to make a test app for Windows 8 that has two input boxes and one button (lets call it "Calculate" button). When the user presses the button he gets a result. He can enter his details in either metric or imperial units by choosing which units he wants to use in the settings flyout. Now what I'm trying to do is to commit the changes instantly. When the user selects for example the imperial units the input boxes and the result automatically change to imperial. Right now when I change the units from metric to imperial I must press the "Calculate" button again to see the results in imperial.
How can I do that?
Below is some of my code.
In the default .js file I created a button handler:
var test = document.getElementById("button");
test.addEventListener("click", doDemo, false);
In the main .js file where all the calculations are done it looks like this:
function doDemo(eventInfo) {
var applicationData = Windows.Storage.ApplicationData.current;
var roamingSettings = applicationData.roamingSettings;
if (roamingSettings.values["cmorft"] == 'imperial') {
var greetingString3 = "Imperial";
document.getElementById("units").innerText = greetingString3;
} else {
var greetingString4 = "metric";
document.getElementById("units").innerText = greetingString4;
}
I used the following to save the user's choice:
var applicationData = Windows.Storage.ApplicationData.current;
var roamingSettings = applicationData.roamingSettings;
WinJS.UI.Pages.define("/html/settings.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var imperialRadio = document.getElementById("imperial"),
metricRadio = document.getElementById("metric");
// Set settings to existing values
if (roamingSettings.values.size > 0) {
if (roamingSettings.values["cmorft"]) {
setMIValue();
}
}
// Wire up on change events for settings controls
imperialRadio.onchange = function () {
roamingSettings.values["cmorft"] = getMIValue();
};
metricRadio.onchange = function () {
roamingSettings.values["cmorft"] = getMIValue();
};
},
unload: function () {
// Respond to navigations away from this page.
},
updateLayout: function (element, viewState, lastViewState) {
// Respond to changes in viewState.
}
If I understand you correctly, you simply need to set the innerText properties of your HTML elements when you change the units, not just when you click the button. In your demo it can be as simple as calling doDemo from within the onchange handlers for your radiobuttons, as that will read the updated setting and set the text.

Showing warning with timeout when opening external links

I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}

Categories

Resources