How to know if we are leaving web page? - javascript

I have a form on my page. If it is changed because beforeunload event the user will have a dialog which catch the leave process.
If the user click on "continue" or "leave" then the new page is loading and form's data are lost.
If the user click on "cancel" the leave process is canceled.
How can we know when the user has clicked on cancel ?
Why I need to know that ?
In my case I have a switch button. When the user turns it on, the script tries to reload the page. If the user click on "continue" or "leave" it's ok. But if the user click on "cancel" I would like show back the switch on the position "off".

When a user changes the button position ON and then attempts to leave but then cancel, the state of the button should change to OFF. We can use window.onbeforeunload function and returning false within the block of its code. Please see the below example, note that I have used checkbox instead of toggle switch, but you can type anything inside the window.onbeforeunload function to your desire.
window.onbeforeunload = () => {
document.getElementById("checkbox").checked = false;
return false;
}
.checkbox {
margin-top: 20px;
margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>
<div>
Click here to exit this site and go to google.com
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox">
</div>

To handle the state of the button, we can use localStorage and setInterval timer to check if the user has left the site and onbeforeunload event to prompt user to leave or cancel. When user cancels, the interval counts down to 0, this means the user is still on your site and updates the localStorage, but if left, the interval will not continue and doesn't change the localStorage value, and therefore, when returning to your site, the checked button should be updated to the previous position. Note that, when you click Run code snippet on this site, it might not work for localStorage, run this code from your site or on JSFiddle. :-)
window.onload = () => {
// declaration & Initialization
const input = document.createElement("input");
const defaultCounterValue = 10; // incremental --
const defaultIntervalValue = 50; // ms
const checkbox = document.getElementById('checkbox');
const setLocalStorage = (itemName, itemValue) => {
localStorage.setItem(itemName, itemValue);
};
const getLocalStorage = (itemName) => {
return localStorage.getItem(itemName) === null ? false : localStorage.getItem(itemName) === 'false' ? false : true;
};
let interval = undefined;
let counter = defaultCounterValue;
setLocalStorage('checkbox', getLocalStorage('checkbox').toString());
setTimeout(() => {
checkbox.checked = getLocalStorage('checkbox');
}, 0);
checkbox.addEventListener('click', () => {
setLocalStorage('checkbox', checkbox.checked);
});
// set input property and event handlers
input.type = 'checkbox';
input.checked = false;
input.style.display = 'none';
input.addEventListener('click', () => {
let removeInterval = () => {
clearInterval(interval);
interval = undefined;
}
if (interval) {
removeInterval();
}
interval = setInterval(() => {
if (input.checked === true) {
if (counter === 0) {
checkbox.checked = false;
setLocalStorage('checkbox', checkbox.checked);
counter = defaultCounterValue;
input.checked = false;
}
counter--;
} else {
removeInterval();
}
}, defaultIntervalValue);
});
document.body.appendChild(input);
// Event that run before the user leaves
window.onbeforeunload = (event) => {
event.preventDefault = true;
event.cancelBubble = true;
event.returnValue = null;
input.checked = false;
input.click();
};
}
.checkbox {
margin-top: 20px;
margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>
<div>
Click here to exit this site and go to google.com
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox">
</div>

Related

Disable or enable buttons if input condition met in JS, While input is auto-generated

i'm newbie in JS.
as in the title, I want to create a disable button when the condition is met based on the following code:
<input class="input" type="text">
<button class="button">Click Me</button>
<script>
let input = document.querySelector(".input");
let button = document.querySelector(".button");
button.disabled = true;
input.addEventListener("change", stateHandle);
function stateHandle() {
if(document.querySelector(".input").value === "") {
button.disabled = true;
} else {
button.disabled = false;
}
}
</script>
value on input is auto generated after 500ms. the code above works if after the input value appears and then I enter any number. what I want is when the input value appears then the button will automatically be in the enable position.
Based on #David's answer, I added new Events and dispatch them later.
This is the updated code :
<script >
let input = document.querySelector("#input");
let button = document.querySelector("#button");
button.disabled = true; //setting button state to disabled
const event = new Event("change"); //adding new event
input.addEventListener("change", stateHandle);
function stateHandle() {
var t = document.getElementById("jarak").value,
check = "luar";
if (new RegExp('\\b' + check + '\\b').test(t)) {
button.disabled = true; //button remains disabled
} else {
button.disabled = false; //button is enabled
}
}
setTimeout(function() {
input.dispatchEvent(event); //dispatching event after 700ms
}, 700);
</script>

How do you uncheck a checkbox when user exits fullscreen in javascript?

I have a checkbox element with the ID "fullscreen." Clicking the checkbox puts the user into fullscreen mode. However, if the user exits the fullscreen mode using f11, the checkbox remains checked.
I am looking for a script which does as follows:
If the checkbox "fullscreen" is checked, and an "onfullscreenchange"
event occurs
Then, uncheck checkbox with the ID "fullscreen."
This is what I have right now:
It does not work--
var el = document.getElementById('fullscreen');
if (el.checked == true){
document.onfullscreenchange = function ( event ) {
el.checked = false;
};
}) );
How do I do this? Please help!
You can use onfullscreenchange event listener with vendor prefixed to listen to fullscreen change and do whatever required, something like.
document.addEventListener("webkitfullscreenchange", function (event) {
var el = document.getElementById('fullscreen');
if(document.webkitFullscreenElement === null) {
elem.checked = false
}
});
Alternatively
["fullscreenchange", "webkitfullscreenchange", "mozfullscreenchange", "msfullscreenchange"].forEach(
prefixed => document.addEventListener(prefixed, function() {
var el = document.getElementById('fullscreen');
el.checked = false;
})
);

Alert on browser close button but not for every load of the page

I want code to alert the user for closing the close button of the browser, but I am getting alert for every loading or for every refresh and tab change inside the web page.
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
You have to save the alert box state anywhere, so that you can check, if the user has seen it once. You could save the state of your alert box for example in a local storage. I changed the code.
First on the onload event, check if there's a localStorage Item "showConfirmation". If not, create one with the string value "true", otherwise just log the value.
Second, on beforeclose it checks if the item has the value "true". If so, return a string to show the alert message.
Third, on window.close you set the item to string "false", the message will not be shown anymore.
window.onload = checkLocalStorage;
window.onbeforeunload = askForClose;
window.unload = checkLocalStorage;
function checkLocalStorage() {
if (localStorage.getItem("showConfirmation") === null) {
localStorage.setItem("showConfirmation", "true");
} else {
console.log(localStorage.getItem("showConfirmation"));
}
}
function askForClose() {
var showConfirmation = localStorage.getItem("showConfirmation");
if (showConfirmation === "true") {
localStorage.setItem("showConfirmation", "false");
return "You really want to close?";
}
}

How to make a function run before a button can be pressed again in JS?

I'm trying to write a program in JavaScript in which certain functions must be performed before a button can be pressed again.
The button performs a function that should only be performed once per turn, but I want other actions to be performed before the next turn, and to have a sort of confirmation before progressing to the next turn. In psuedocode it might look something like this:
buttonFunction();
actionOne();
actionTwo();
turnOverConfirm();
etc.
But I'm not so sure how to do that. Right now the button can be pressed at any time. How do I make it so that the user must confirm before the button can be pressed again?
You can disable and enable buttons via javascript. You could block it like that:
document.getElementById("button").disabled = true
Just set it to false again to make it clickable again!
You can use the javascript confirm function. This function will popup a message box with ok and cancel
Here is an example
var r = confirm("Press a button!");
if (r == true) {
alert("OK was clicked");
} else {
alert("Cancel was clicked");
}
What you can do is when a user clicks on a button, popup a confirm box, then if they click ok you can then run the function you listed above.
There are few ways
You can hide the button till processing is ready or replace with an "please wait..." image
You can create an prevent varaible or remove temporary click event function
var Action = (function(){
var prevent = false;
function _start() {
if (prevent === false) {
prevent = true;
_process();
}
}
function _process() {
// DO Action
prevent = false;
}
return { start: _start }
})();
Fire
you can make event for evry click here is an example with alert and change button color all in one function
var clicked = 0;
var btn = document.getElementById("btn");
function clickBtn(){
if (clicked == 0) {
alert("it's first click");
btn.style.background = "black";
clicked = 1;
}else if (clicked == 1) {
alert("it's second click");
btn.style.background = "orange";
clicked = 2;
} else if (clicked == 2) {
alert("it's third click");
btn.style.background = "green";
clicked = 3;
}
}
#btn{
border-radius:15px 0 15px 0;
color:white;
border:none;
padding:15px;
background:blue;
font-weight:bold;
}
#btn:hover{
border-radius:0 15px 0 15px;
}
<button id="btn" onclick="clickBtn()">Click Me</button>

contenteditable on doubleclick

I've got a p tag with some text, and I'm trying to make it contenteditable but only on doubleclick. How can I prevent browser from placing the cursor on the p when I click on it and only do it when I doubleclick? JQuery:
p.dblclick(function(e){
p.css("cursor", "text");
})
.focusout(function(){
p.css("cursor", "default");
})
.click(function(e){
console.log('focus p');
e.stopPropagation();
$("body").focus(); // not stopping Chrome from placing cursor
});
I could make contenteditable false by default and then make it true on dbleclick and then do p.focus() but it means I can't place cursor where I clicked. On the other hand, I could make it contenteditable after first click and then wait like 1.5s for a dobuleclick and if it didn't happen cancel it, but if it happened, then the content would be editable and the second click would trigger the placement of the cursor in the right place. However, it's not that smooth and makes the content editable for these 1 and a half seconds.
Any ideas?
answer:
In case somebody is interested, I went on to implement the timer method, because I don't think there's any other way... here's the code
var DELAY = 700, clicks = 0, timer = null;
p.focusout(function(){
p.css("cursor", "default");
p.prop("contenteditable", false);
})
.click(function(e){
clicks++;
p.prop("contenteditable", true);
if(clicks == 1){
timer = setTimeout(function() {
p.prop("contenteditable", false);
//alert("Single Click"); //perform single-click action
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
// alert("Double Click"); //perform double-click action
clicks = 0; //after action performed, reset counter
}
});
try this here a working fiddle
<p ondblclick="this.contentEditable=true;this.className='inEdit';" onblur="this.contentEditable=false;this.className='';" contenteditable="false" class="">This paragraph uses some simple script to be editable. Double-click the text to begin editing.</p>
Here is a solution which works for me:
<script>
function listenForDoubleClick(element) {
element.contentEditable = true;
setTimeout(function() {
if (document.activeElement !== element) {
element.contentEditable = false;
}
}, 300);
}
</script>
<p onclick="listenForDoubleClick(this);" onblur="this.contentEditable=false;">Double-click the text to begin editing.</p>
Here is a working fiddle: https://jsfiddle.net/dtL3xzfb/
It uses a timeout event to check if the text has been selected within a certain period of time (300ms), if the text is not selected (by a second click) it will set content editable to false again: The content editable parameter is set to true after the first click so text will be selected when you click for a second time.
You could make the text unselectable as in How to disable text selection using jQuery? :
var p = $('p');
p.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
p.dblclick(function (e) {
p.css("cursor", "text")
.attr('contenteditable', true)
.attr('unselectable', 'off')
.css('user-select', 'inherit')
.off('selectstart', false)
.focus();
});
p.focusout(function () {
p.css("cursor", "default")
.attr('unselectable', 'on')
.attr('contenteditable', false)
.css('user-select', 'none')
.on('selectstart', false);
});
If using React you may use the component
import _ from 'lodash'
import { useState } from 'react'
const inputValue = (e: any): string => e.target.value
function isEnterOrEscapeKeyEvent(event: React.KeyboardEvent<HTMLInputElement>) {
return event.key === 'Enter' || event.key === 'Escape'
}
const EditOnDblClick = () => {
const [isEditing, setisEditing] = useState(false)
const [text, settext] = useState('yoga chitta')
const onEditEnd = () => {
setisEditing(false)
}
return isEditing ? (
<input
value={text}
className="bg-transparent border-2 border-black border-solid"
onKeyDown={(event) => {
if (isEnterOrEscapeKeyEvent(event)) {
event.preventDefault()
event.stopPropagation()
onEditEnd()
}
}}
onChange={_.flow(inputValue, settext)}
onBlur={onEditEnd}
autoFocus
/>
) : (
<div className="select-none" onDoubleClick={() => setisEditing(true)}>
{text}
</div>
)
}
export default EditOnDblClick
Note: Classes are from tailwindcss

Categories

Resources