i have this code that checks if the user has logged in or not, if the user has not logged in, it redirects the user to the login page to log in and if he/she has logged in, they would be allowed to upload content on the page. this is the code:
let vocals = document.getElementsByClassName("up");// class name of certain divs in the program
for (let i = 0; i < vocals.length; i++) {
vocals[i].addEventListener("click", () => {
let check = "php/checkCookie.php";
fetch(check, { method: "GET" })
.then((res) => res.text())
.then((data) => {
if (data == 0) {
shout("Login Before You Can Create", 0);
setInterval(() => {
location.href = "logincheck.html";
}, 3000);
} else {
document.getElementById(`e${i}`).click();
}
});
...
});
}
the code:
document.getElementById(`e${i}`).click();
is supposed to open the file explorer so that the user can pick a file and upload, but it doesn't work, and it does not show an error.
those anyone know why and has a solution, thanks in advance
Maybe your element doesn't support click() on it? If I remember correctly, click() works on on several elements, but not all. It should work on <input>, and <a>.
You could also try this instead:
document.getElementById(`e${i}`).dispatchEvent(new MouseEvent('mousedown'))
document.getElementById(`e${i}`).dispatchEvent(new MouseEvent('mouseup'))
Related
I have strange problem with buttons that are requesting for displaying templates on client page.
This is client side code. The main task of entire class is to just enable user to click button, send request and get response with HTML that has been rendered from handlebars template and just paste it in partiuclar place on client side. It works, but only once. After first click and displaying elements, I totally lose any interaction with those buttons. There is no request, and there is no even EventListener for clicking. I get no error. Completely there is no single reaction after clicking.
class Weapons {
constructor() {
this.buttons = document.querySelectorAll('.type')
}
async displayWeapon(path) {
const container = document.querySelector('.shop-container')
await fetch(`weapons/${path}`).then(response => response.json()).then(data => container.innerHTML += data);
}
chooseWeapon() {
this.buttons.forEach(btn => {
btn.addEventListener('click', (e) => {
console.log('click');
let weaponType = e.target.dataset.type
switch (weaponType) {
case 'pistols':
console.log('click');
return this.displayWeapon(weaponType)
case 'rifles':
console.log('click');
return this.displayWeapon(weaponType)
case 'grenades':
console.log('click');
return this.displayWeapon(weaponType)
case 'closerange':
console.log('click');
return this.displayWeapon(weaponType)
case 'rocketlauchner':
console.log('click');
return this.displayWeapon(weaponType)
}
})
})
}
}
document.addEventListener('DOMContentLoaded', function () {
const weapons = new Weapons();
weapons.chooseWeapon();
> When I invoke displayWeapon(path) here it also works, but immidiately
> after displaying html elements clicking on buttons again does not
> initiate any action.
})
Here is app.get function but I doubt it's source of problem.
app.get('/weapons/:id', (req, res) => {
console.log('req');
console.log(req.url);
let type = req.params.id;
res.render(type, function (err, html) {
res.json(html);
})
})
Ok. The answer is actually simple. In fetch function container.innerHTML += data. This line deletes my html with buttons, and the same time it deletes eventListeners. So I need just to modify my html.
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
I want to know how to make a Tab highlight everytime an event happens, in this case, it would be a call. So, if the user isn't in my website in the moment, he will know that a event happenned. My useEffect looks like the following:
useEffect(() => {
if (newCall < calls.length){
setHighlight(true)
setNewCall(calls.length)
}
}, [calls.length])
useEffect(() => {
if (newCall < calls.length){
setHighlight(!'your state name')
setInterval(()=>setHighlight(!'your state name'),2000)
setNewCall(calls.length)
}
}, [calls.length])
The above fragment of code sets highlight and so does the user knows that an event has happened and after 2 seconds the highlight will be returned to the initial state.
It seems as though the solution is a combination of:
Browser tab change notification like when you get a new gmail e-mail or a new tweet in Twitter
and
Detect If Browser Tab Has Focus
useEffect(() => {
window.onfocus = function(){
document.title = "Original Title"
}
return () => {
window.onfocus = null;
}
}, []);
useEffect(() => {
if (newCall < calls.length){
document.title = `Original Title (${calls.length} calls)`
}
}, [calls.length])
I'm really new to javascript and jquery and I'm trying to get a button to autoclick from an existing code base. I am having trouble getting the button to do that even though this is what I've been following How to auto click an input button.
The code is below. I've tried using both .submit() and .click() but the start-game-btn doesn't seem to get pressed either way. I've put a console.log within the button whenever it's pressed and the message doesn't seem to get logged.
console.log("loading...")
$(() => {
$("#start-game-btn").click(event => {
console.log("start-game")
$("#errors").text("")
event.preventDefault()
const height = parseInt($("#height").val())
const width = parseInt($("#width").val())
const food = parseInt($("#food").val())
let MaxTurnsToNextFoodSpawn = 0
if ($("#food-spawn-chance").val()) {
MaxTurnsToNextFoodSpawn = parseInt($("#food-spawn-chance").val())
}
const snakes = []
$(".snake-group").each(function() {
const url = "http://0.0.0.0:8080/"//$(".snake-url", $(this)).val()
console.log(url)
if (!url) {
return
}
snakes.push({
name: "M1",//$(".snake-name", $(this)).val(),
url
})
})
if (snakes.length === 0) {
$("#errors").text("No snakes available")
}
console.log(12)
fetch("http://localhost:3005/games", {
method: "POST",
body: JSON.stringify({
width,
height,
food,
MaxTurnsToNextFoodSpawn,
"snakes": snakes,
})
}).then(resp => resp.json())
.then(json => {
const id = json.ID
fetch(`http://localhost:3005/games/${id}/start`, {
method: "POST"
}).then(_ => {
$("#board").attr("src", `http://localhost:3009?engine=http://localhost:3005&game=${id}`)
}).catch(err => $("#errors").text(err))
})
.catch(err => $("#errors").text(err))
})
console.log("ready!")
})
window.onload = function(){
var button = document.getElementById('start-game-btn');
button.form.submit();
console.log("Done!!")
}
Everytime I refresh the page the log shows:
loading...
ready!
Done!!
What I think it should be logging is (or at least that's what I'm trying to achieve):
loading...
start-game
ready!
Done!!
submit() does not work because it is for submitting forms.
button.form.submit(); does not work because it assumes your button is part of a form.
As it looks like you are using jQuery, try just calling the jQuery click function without any parameters using a jQuery selector.
eg.
$("#start-game-btn").click();
I have service worker which handles push notification click event:
self.addEventListener('notificationclick', function (e) {
e.notification.close();
e.waitUntil(
clients.openWindow(e.notification.data.url)
);
});
When notification comes it takes url from data and displays it in new window.
The code works, however, I want different behavior. When User clicks on the link, then it should check if there is any opened window within service worker scope. If yes, then it should focus on the window and navigate to the given url.
I have checked this answer but it is not exactly what I want.
Any idea how it can be done?
P.S. I wrote this code but it still doesn't work. The first two messages are however shown in the log.
self.addEventListener('notificationclick', function (e) {
e.notification.close();
var redirectUrl = e.notification.data.redirect_url.toString();
var scopeUrl = e.notification.data.scope_url.toString();
console.log(redirectUrl);
console.log(scopeUrl);
e.waitUntil(
clients.matchAll({type: 'window'}).then(function(clients) {
for (i = 0; i < clients.length; i++) {
console.log(clients[i].url);
if (clients[i].url.toString().indexOf(scopeUrl) !== -1) {
// Scope url is the part of main url
clients[i].navigate(givenUrl);
clients[i].focus();
break;
}
}
})
);
});
Ok, here is the piece of code which works as expected. Notice that I am passing scope_url together with redirect_url into the web notification. After that I am checking if scope_url is part of sw location. Only after that I navigate to redirect_url.
self.addEventListener('notificationclick', function (e) {
e.notification.close();
var redirectUrl = e.notification.data.redirect_url;
var scopeUrl = e.notification.data.scope_url;
e.waitUntil(
clients.matchAll({includeUncontrolled: true, type: 'window'}).then(function(clients) {
for (i = 0; i < clients.length; i++) {
if (clients[i].url.indexOf(scopeUrl) !== -1) {
// Scope url is the part of main url
clients[i].navigate(redirectUrl);
clients[i].focus();
break;
}
}
})
);
});
If I understand you correctly, most of the code you linked to works here.
First retrieve all the clients
If there are more than one, choose one of them
Navigate that to somewhere and focus
Else open a new window
Right?
event.waitUntil(
clients.matchAll({type: 'window'})
.then(clients => {
// clients is an array with all the clients
if (clients.length > 0) {
// if you have multiple clients, decide
// choose one of the clients here
const someClient = clients[..someindex..]
return someClient.navigate(navigationUrl)
.then(client => client.focus());
} else {
// if you don't have any clients
return clients.openWindow(navigationUrl);
}
})
);