Is it possible to both download and open pdf file in a new tab by clicking one link by means of html only?
If I need to use JS, could you possibly direct me to the similar thread?
For downloading I used download attribute in the link, but how can I do both in one link simultaneously?
Category: javascript
Category Added in a WPeMatico Campaign
How to recognize if a device is going off a given route?
I am in a situation:
- I store my google map direction result from given 2 points on map in an array of JS object like {Lon: float, Lat: float}
- I collect my real time location and log my current Lon and Lat
How can I programmatically find out where the location located in the array and recognize if the current location is going off the route stored in the array?
Really appreciate if you can visual it with concept and code.
I can only think of finding the position in the array by going through the array and calculate the distance of the current location with each item. But there is a situation where I have passed that point, so doing things after is kind of messed up.
Why are my dives not showing up on browser?
`const divArray = [];
const grid = document.getElementById('grid');
var hs = document.getElementsByTagName('h1');
for(let i = 0 ; i< 10 ; i++){
const div = document.createElement('div');
div.className +='grid-box';
divArray.push(div);
}
document.getElementById('id').textContent="Hay their,"
console.log(divArray);
for(let i = 0 ; i< 10 ; i++){
divArray[i].style.height='20px';
divArray[i].style.width='20px';
divArray[i].style.color="black";
document.body.appendChild(divArray[i]);
}`
VS code by the way.
No errors, no warnings,
No mistake with liking script.
Then what is it?
GetBoundingClientRect() returns an overflowing child as being shorter than it’s parent
I have this arrangement, where the child is overflowing it’s parent:
I would like to detect this condition; I attempted to use getBoundingClientRect(). However, I’m afraid the results have been confounding to me. The <div> (as seen by the inset rectangle) is being reported as having greater width than the <h3>. Obviously, the title “primitive” is much longer than the div which serves as it’s parent.
(child is the html element of the <h3>, and this.node refers to the <div> which constitutes the red box.)
Could someone please explain this behavior?
PS: The ultimate goal is to resize the parent node to fit arbitrary children, but I can’t get the required information into the algorithm per this problem. If someone has a CSS way to do that, I’m not in love with this method.
PS #2: I’m also curious why the child’s background color is only applied to the parent, is this related?
Change interval multipling it by a number inside an array using react
I want to modify the timing at which console.log(prevIndex) is displayed by adjusting the speed array using currentLocationIndex to iterate over [1, 5, 6, 2, 3, 4]. The current code does not produce the expected behavior. Thanks in advance for any assistance from those willing to help.
import { useState } from 'react';
import './App.css';
function App() {
const [speed, setSpeed] = useState([1, 5, 6, 2, 3, 4]);
const [location, setLocation] = useState([10, 20, 13, 20, 10, 2]);
const [currentLocationIndex, setCurrentLocationIndex] = useState(0);
function updateLocation() {
const interval = setInterval(() => {
setCurrentLocationIndex((prevIndex) => {
console.log(prevIndex);
if (prevIndex < location.length - 1) {
console.log(prevIndex);
return prevIndex + 1;
} else {
clearInterval(interval);
return prevIndex;
}
});
}, 1000 * speed[currentLocationIndex]);
}
return (
<div>
<button onClick={updateLocation}>Initiate</button>
</div>
);
}
export default App;
I was expecting that the time interval would change with this line of code:
1000 * speed[currentLocationIndex])
http request is over and succeeds ,but I can not get response or response comes later
As the title describes, The front end raises a request to the backend. From the chrome panel,I think the request is over ,but I can not get response or response comes later.
The following images are what I meet.Many thanks.
the request is over and succeeds
get no response
I want to know why this happen and how I can solve this problem
react-slick slider Custom arrows
I am using react-slick library for slider component, my Slider component contains 8 slides , initially , my previous and next buttons are working fine , i want the next button should be disabled when there no slides are left to move , previous button is working fine , but next button is not working properly .
Here in the above image you can see the next button is still enabled and i am able to click even there are no slides to move , i want this next arrow to be disabled, when there are no slides.
this is my code
const settings = {
dots: false,
infinite: false,
speed: 500,
slidesToShow: 3,
slidesToScroll: 3,
nextArrow: ,
prevArrow: ,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
},
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
initialSlide: 2,
},
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
},
},
],
}
function NextButton(props) {
const { className, style, onClick } = props
return (
<div
id=”next”
className={className}
style={{ …style }}
onClick={onClick}
>
)
}
function PrevButton(props) {
const { className, style, onClick } = props
return (
<div
id=”prev”
className={className}
style={{ …style }}
onClick={onClick}
>
)
}
, i want this next arrow to be disabled, when there are no slides.
Problem having multiple user sessions in express-session
I have a problem for a few days and I could not find a solution, I have searched forums, documentation and nothing.I have a website developed in nodejs, using express-session and passport for session management and user authentication.
My problem is that having two different users connected to my website and do an action simultaneously, the website is loaded but with the session of the last user who has performed the action. In other words, it uses a session for the rest of the users who have performed the action simultaneously.
This is my base configuration of my website
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const exphbs = require('express-handlebars');
const session = require('express-session');
const validator = require('express-validator');
const passport = require('passport');
const flash = require('connect-flash');
const MySQLStore = require('express-mysql-session')(session);
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const helmet = require("helmet");
const { database } = require('./keys');
// Intializations
const app = express();
require('./lib/passport');
// Settings
app.set('port', process.env.PORT || 4000);
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', exphbs({
defaultLayout: 'main',
layoutsDir: path.join(app.get('views'), 'layouts'),
partialsDir: path.join(app.get('views'), 'partials'),
extname: '.hbs',
helpers: require('./lib/handlebars')
}))
app.set('view engine', '.hbs');
// Middlewares
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
secret: '1234567789',
key: "namecookie",
resave: true,
saveUninitialized: true,
store: new MySQLStore(database),
cookie: {
secure: false,
maxAge: 150000,
httpOnly: false
}
}));
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(validator());
// Global variables
app.use((req, res, next) => {
app.locals.message = req.flash('message');
app.locals.success = req.flash('success');
app.locals.user = req.user;
next();
});
// Routes
app.use(require('./routes/index'));
app.use(require('./routes/authentication'));
app.use('/links', require('./routes/links'));
// Public
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());
// Starting
app.listen(app.get('port'), () => {
console.log('Server is in port', app.get('port'));
});
Google Sheet to Google Calendar Integration
I am a beginner, writing a code for google sheet to create event on google calendar based on data entered on a google sheet. My start Date and end date is written in this format: yyyy”, “m”, “d”, “h”, “m”, “s for example : on cell Z2 it is written as: 2023, 2, 1, 11, 0, 0. Time Zone on my google calendar is set to GMT+07:00. The code has successfully create event on the right date but the time is always wrong for example on cell Z2 the script has successfully created an event on 2 February 2023 but the time of event is logged incorrectly (00:00 – 01:00) when it should be (11:00 – 12:00). Can anyone help me identify whether the problem is in my datetime format on the google sheet or is it on the code itself instead? Any help is appreciated.
here is the code i have tried:
function createEvent() {
var spreadsheet = SpreadsheetApp.openById('SpreadsheetId');
var sheet = spreadsheet.getSheetByName('SheetName');
var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
var calendar = CalendarApp.getCalendarById('Calendar ID');
for (var i = 0; i < data.length; i++) {
var row = data[i];
var title = row[31]; // Column AF
var description = row[3]; // Column D
var startDate = new Date(row[25]); // Column Z
var endDate = new Date(row[26]); // Column AA
var event = calendar.createEvent(title, startDate, endDate, { description: description });
Logger.log('Event ID: ' + event.getId());
}
}
Trying to populate Dropdown box using an API call is not populating the dropdown [duplicate]
Right now I’m working on a site that users will be able to create a backlog directory of their games owned. I’ve got everything working the way I want it to but I’m trying to get the “platform” dropdown to populate with the platforms available for the games. I’m using the IGDB API right now to try to do that. This is my code to fetch the data:
const twitchAccessToken = "<?php echo $authData['access_token']; ?>";
async function fetchSystemNames() {
try{
const response = await fetch('https://api.igdb.com/v4/platforms', {
method: 'GET',
headers: {
'Client-ID': 'mdx5fxydmiksf444vdy27o8dch2v94',
Authorization: 'Bearer ${twitchAccessToken}'
}
});
const data = await response.json();
if(!response.ok) {
throw new Error(data.error || 'Failed to fetch system names');
}
return data;
} catch (error) {
console.error('Error fetching system names', error.message);
return [];
}
}
The “access_token” is found earlier in the code and I know that part is working b/c I’m using the standard Twitch API to find the games in the first place. In the console when the site is ran I’m getting this error: “Access to fetch at ‘https://api.igdb.com/v4/platforms’ from origin ‘http://localhost’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.” I don’t know what that means and chatgpt hasn’t been much help figuring it out. This is my code for populating the dropdown:
async function populateSystemDropdown() {
const systemDropdown = document.getElementById('system');
// Fetch system names
const systemNames = await fetchSystemNames();
// Populate the dropdown
systemNames.forEach(name => {
const option = document.createElement('option');
option.value = name;
option.textContent = name;
systemDropdown.appendChild(option);
});
}
populateSystemDropdown();
I’ve been using chatgpt to help look at the code and adjust it. What I’d like for it to do is fetch the platform names from the IGDB database and then put them into a dropdown box.
how to use stackoverflow [closed]
i was learning to use stack over flow as i,am a very beginner in the programming can you guys give me any tips you guys might wanna share
import React, { useEffect, useState } from ‘react’
import axios from "axios" const Allvideos = () => { const [data, setData ] = useState("") const likeVideo = (id)=>{ axios.put(http://localhost:4999/like/${id}`) } useEffect(() =>{ axios.get("http://localhost:4999/getvideos").then((data) => { setData(data.data) console.log(data.data) }) }, []) return ( <div> {Array.isArray(data) ? data.map((datas) =>( <div key={datas._id}> <h1>{datas.title}</h1> <p>{datas.desc}</p> ` <button onClick={() => likeVideo(datas._id)}>{datas.likes.length}likes</button> <button>{datas.dislikes}dislikes</button>
</div>
)) : <p>
sorry no videos
</p>
}
</div>
)
}
export default Allvideos
thank you
i tried many
none worked
How to get the selected calendar date using Pikaday
I’m new to using a pre-made calendar such as Pikaday. I just can’t seem to grasp how to get the selected calendar date. The code I see online to do that just doesn’t work for me so I must be doing something wrong.
I am getting the error “field is not defined”.
Can someone please point me in the right direction? Thank you so much.
var picker = new Pikaday({
field: document.getElementById('id_pikaday_datepicker'),
onSelect: function(date) {
field.value = this.getMoment().format('Do MMMM YYYY');
console.log(field.value);
}
});```
How to avoid that IntersectionObserver cause a flickering behavior
I am adding an sticky nav in my website using IntersectionObserver, when the isIntersecting passed from true to false, the website and nav starts flickering, in the background the isIntersecting start a loop between true and false causing this flickering behavior.
This is the JS code when I am applying the IntersectionObserver
const nav = document.querySelector(".nav-container");
const sticky = function (entries) {
const [entry] = entries;
console.log(entry);
if (!entry.isIntersecting) {
nav.classList.add("sticky");
} else {
nav.classList.remove("sticky");
}
};
const navObserver = new IntersectionObserver(sticky, {
root: null,
threshold: 0,
});
navObserver.observe(nav);
This is the CSS
.nav-container {
width: 100%;
height: 10vh;
position: relative;
border-bottom: 1px solid rgba(0, 0, 0, 0.5);
}
.nav-container.sticky {
position: fixed;
z-index: 5;
}
My expectation is to keep the nav fixed to the top once this one is set to isIntersecting=false, meaning that when I scroll down I want to keep visible the nav, I did it successfully in another project but not in this one.
Python/Javascript Websocket disconnects after first message
I have this python code (Server)
async def chatProcess(websocket):
message = await websocket.recv()
print(f"<<< {message}")
ints = predict_class(message)
res = get_response(ints, intents)
print("Category"+ints)
await websocket.send(res)
print(f">>> {res}")
async def main():
async with websockets.serve(chatProcess, "localhost", 8765):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
and this javascript client in my webpage
let websocket = new WebSocket("ws://localhost:8765");
const generateResponse = (chatElement) => {
const messageElement = chatElement.querySelector("p");
try{
websocket.send(userMessage);
websocket.onmessage = function(event) {
messageElement.textContent = event.data;
console.log("[message] Data received from server:"+ event.data);
return false;
};
} catch(error) {
console.log(error)
messageElement.classList.add("error");
messageElement.textContent = "Somethings wrong. Try Again";
} finally{
chatbox.scrollTo(0, chatbox.scrollHeight);
}
But keeps disconnectong after first message and get this error
What can I do so that it doesn’t disconnect and I can send messages between client and server?
How to check password and confirm password matches and then only call an API without submitting form (not using state)?
I just got a reference from the solution
How to set match password in react Js
this.state = {
password: '',
confirmPassword: ''
}
handleSubmit = () => {
const { password, confirmPassword } = this.state;
// perform all neccassary validations
if (password !== confirmPassword) {
alert("Passwords don't match");
} else {
// make API call
}
}
I want to check two password fields without submitting the form using Formschema, but not the state since I believe the state is filled just after the form is submitted.(not the state and if condition)
I may or may not be correct, because I am not into the front-end technologies and just facing this condition for the first time.

