Event Listener not working in cookie modal - javascript

first time caller here, please be gentle..
I am in the process of my JavaScript reflection and having a problem with the cookie modal. You need to be able to have the cookie pop up upon entering the site, the user needs to click ok, it is stored locally, and doesn't pop up if the user refreshes the browser.
I have created a basic modal and written the JavaScript, which partly works, but the eventHandler isn't working.
The cookie value is false, which you can see in the console, but when you click the button, it doesn't turn to true.
I have put the code below and if anyone could help I'd really appreciate it.
<div id ="overlay">
<div class="modal">
<p>
</p>
</div>
<button class="settings_button">CHANGE SETTINGS</button>
<button class="modal_accept_button">ACCEPT COOKIES</button>
<button class="modal_accept_button">Accept</button>
</div>
let modalObject = document.querySelector(".modal");
let modalSettings = document.querySelector('.settings_button');
let modalAccept = document.querySelector('.modal_accept_button');
let modalOverlay = document.querySelector("#overlay");
function showModal() {
modalObject.classList.remove('deactive');
modalOverlay.classList.remove('deactive');
}
function disableModal() {
modalObject.classList.add('deactive');
modalOverlay.classList.add('deactive');
}
localStorage.setItem('cookie', 'false');
window.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('cookie') == 'true') {
console.log("Cookie is already in place.");
} else if (localStorage.getItem('cookie') === null ||
localStorage.getItem("Cookie accepted") == 'false') {
console.log("Cookie has been not yet been accepted.");
showModal();
modalAccept.addEventListener('click', () => {
localStorage.setItem('cookie','true');
disableModal() ;
});
}
});

You have localStorage.setItem('cookie', 'false'); in your code and this changes your ls to false every time that your codes run, just remove it and I think it's better if you save your local storage in a variable then use that variable in your if statement:
const modal = document.querySelector('.modal');
const acceptBtn = document.querySelector('#acceptCookies');
(() => {
const isCookieAccepted = JSON.parse(window.localStorage.getItem('cookie'));
if (isCookieAccepted) {
alert(`Cookie status: ${isCookieAccepted}`)
} else {
modal.classList.add('show')
}
})();
acceptBtn.addEventListener('click', () => {
window.localStorage.setItem('cookie', true);
modal.classList.remove('show')
})

In your code, you have a line that sets it to false:
localStorage.setItem('cookie', 'false');
This will always set it to false every time you go to that page. So even if you set it to true, when you refresh it will be back to false again.
Removing that line should work, as you dont need to set it to false

Related

How can i execute a function after a form submission causes a page refresh?

I am using shopify's built in customer create, login, reset form submissions which on submit, forces the page to refresh. My intention is to show a message that shows after the page has been refreshed via a button click function. This is what i have so far; The message shows until that page refreshes and then the active class is removed as you would expect.
$(document).ready(function () {
class Alert {
constructor() {
this.customerAlert = document.createElement('div');
}
init(){
this.customerAlert.classList.add('customer-alert');
document.querySelector('body').append(this.customerAlert);
}
show(message){
this.customerAlert.textContent = message;
this.customerAlert.classList.add('active');
setTimeout(() => {
this.customerAlert.classList.remove('active');
}, 8000);
}
}
//create snackbar and initiate
const alertMessage = new Alert();
alertMessage.init();
const createAccountButton = document.querySelector('input.account-trigger');
createAccountButton.addEventListener('click', () => {
alertMessage.show('Your account in now under review');
});
});
Set a boolean variable in session storage just prior to the submit to represent the two states, and then read it in after the refresh.
Something like this:
function HandleFlag(){
var F=sessionStorage.getItem('Flag');
if(F=='1'){
// display your message box here
sessionStorage.setItem('Flag','0');
} else {
// the state is "0" so toggle it just before submitting
sessionStorage.setItem('Flag','1');
}
}
I hope you get my drift.

Chrome Extension Popup Resets On Closing

I'm trying to figure out how to make a play/pause functionality for my chrome extension. I've figured it out and it works however, for usability I now am trying to get the popup window to:
Keep the checkbox checked if it was before closing the popup.
Keep the content that popup.js wrote into a span tag before closing the popup.
My popup.html is:
<script src="popup.js"></script>
<div class="container">
<div class="checkbox">
<p>Check the box to pause the extension</p>
<input type="checkbox" id="switcher" name="switcher">
<p><span id="extensionStatus"></span></p>
</div>
<a id="submit" href="#">Save</a>
</div>
And my popup.js is:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
if(switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
chrome.storage.sync.set({'status': status});
chrome.storage.sync.get('status', function (result) {
status = result.status;
updateStatus.innerHTML = "Current Status: " + status;
if(status == "paused") {
switcher.checked = true;
}
});
});
});
I set have to set the value in storage as I also use the value to do other code on content-script file.
Basically where the line that writes the innerHTML and then the line that sets the checkbox to checked run fine when the popup is open and then as soon as you close the popup and reopen obviously the session resets.
I know it needs something like this in the popup.js instead but I am not quite sure what to put in the function in the background.js as I can't/don't know how to access the popup DOM from background.js:
var backgroundPage = chrome.runtime.getBackgroundPage();
backgroundPage.savePopup();
I don't know how extension storage works but here's a demo which works with local storage. Maybe it can help you with the extension.
Demo
document.addEventListener('DOMContentLoaded', function() {
if (localStorage.getItem('status') == 'paused') {
switcher.checked = true;
}
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
console.log('staus:', localStorage.getItem('status'));
if (switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
localStorage.setItem('status', status);
});
});

How to get my button to work using javascript?

I am creating an Google chrome extension and I am trying to get my stop/stop logging button to work within my function named Logger. When the button is pressed it doesn't react to the function I wrote, Currently it is displaying the stop-button but I want it to display the start-button when clicked. I hope I explained that to some understanding but do anyone possibly know why my function is not working?
Below is my current javascript function and html :
popup.js
//attempt to get start/stop logging buttons to work
function Logger(isLogging, notLogging) {
if (isLogging = true, notLogging = false) {
addRow();
document.getElementById("click-start").style.display = "block";
document.getElementById("click-stop").style.display = "none";
}
if (isLogging = false, notLogging = true) {
document.getElementById("click-start").style.display= "none";
document.getElementById("click-stop").style.display= "block";
}
}
//button to start logging
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-start").addEventListener("click", Logger(true, false));
});
//button to stop logging
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-stop").addEventListener("click", Logger(false, true));
});
popup.html
<!--Start button of logging-->
<button class="button button1" id="click-start" >
<u> Start Logging </u>
</button>
<!--Stop button of logging-->
<button class="button button2" id="click-stop" >
<u> Stop Logging </u>
</button>
Image of current output--button currently doesnt react
This may help to get the core functionality working, this implementation can be much improved
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//attempt to get start/stop logging buttons to work
function Logger(isLogging) {
console.log(isLogging)
if (isLogging) {
btnStart.style.display = "block";
btnStop.style.display = "none";
}else{
btnStart.style.display = "none";
btnStop.style.display = "block";
}
}
//button to start logging
document.addEventListener("DOMContentLoaded", function () {
btnStart.addEventListener("click", function() {Logger(false)});
btnStop.addEventListener("click", function() {Logger(true)});
});
You have to try to keep the queries to the DOM to a minimum.
Have a look at the toggle method it will help to make your code a bit leaner and easier to maintain
I'm not sure if the Logger function gets executed if you use it like this in the addEventListener.
Maybe you can give it a try like this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-start").addEventListener("click", function () {
Logger(true, false))
};
});

React - check when tab or browser is closed, but not on refresh

I want to disconnect all my users when the tab is closing or the browser is getting closed, so far so good. But when I refresh the page, all my users get disconnected too, this should not happen on refresh. Is it possible to avoid to execute this event on refresh? I saw some users doing with localStorage, but I still didn't get the point.
componentDidMount() {
this.beforeUnloadListener();
}
beforeUnloadListener = () => {
window.addEventListener("beforeunload", (ev) => {
ev.preventDefault();
// code to logout user
});
};
The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.
Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
Have done this on react application and its work for me on index.html file write this in script tag.
<script type="text/javascript">
window.addEventListener("beforeunload", (event) => {
window.localStorage.isMySessionActive = "true";
});
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
</script>
Then go on main file and write this code.
useEffect(() => {
// define increment counter part
const tabsOpen = localStorage.getItem("tabsOpen");
if (tabsOpen == null) {
localStorage.setItem("tabsOpen", 1);
} else {
localStorage.setItem("tabsOpen", parseInt(tabsOpen) + parseInt(1));
}
// define decrement counter part
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
window.localStorage.isMySessionActive = "false";
} else {
const newTabCount2 = localStorage.getItem("tabsOpen");
let value = localStorage.getItem("isMySessionActive");
if (value == "true") {
if (newTabCount2 - 1 == 0) {
localStorage.clear();
window.localStorage.isMySessionActive = "false";
} else {
window.localStorage.isMySessionActive = "false";
}
}
}
}, []);

reset webpage to its initial state

I have written a clear function which is supposed to clear map and combo box. But I want to reset the webpage to its initial state. I have tried APP.restart()
App.restart = function() {
var child,
child_process = require("child_process"),
gui = require('nw.gui'),
win = gui.Window.get();
if (process.platform == "darwin") {
child = child_process.spawn("open", ["-n", "-a", process.execPath.match(/^([^\0]+?\.app)\//)[1]], {detached:true});
} else {
child = child_process.spawn(process.execPath, [], {detached: true});
}
child.unref();
win.hide();
gui.App.quit();
}
But nothing works.
I do not need to reload function. Can anyone tell how to reset the webpage to its initial state?
Follow any one of this:
1.Prevent page from caching (with response headers from server);
2.Clear all fields each time page is loaded with Javascript.
Example with jQuery:
<script>
$(document).ready(function(){
$('your_form_input_fields_id').val('');
});
</script>
See this link: reset webpage

Categories

Resources