When I run the html with the VScode live server, everything runs normally and the script inserted with get the media normally, but when I start serving this html through an express server, the navigator.mediaDevices.getUserMedia( ) doesn’t work as it returns null//undefined, how to solve?
Category: javascript
Category Added in a WPeMatico Campaign
Customizing Google Maps Clusters
I’m a beginner web developer who is experimenting with the Google Maps API for the first time. After some trial and error I was able to get map clusters working on my project but am struggling to understand how to customize them to match the aesthetics of my site. The documentation says to “Customize the cluster icon through the renderer interface” but clicking the provide link doesn’t provide any steps on that process.
Thanks in advance! I greatly appreciate any help or advice.
How to make iOS keyboard display when focusing on new contentEditable div?
I’m making a To Do app and when the user hits the “New Task” button, it creates a new “task” element and inserts it into the DOM. Within this element is a contentEditable div (taskNameDiv) that displays placeholder text.
Once the new task element is added to the DOM, the program should immediately direct focus to taskNameDiv so the user can change the placeholder text to the real task name.
With the below code, I’m successfully able to direct focus to taskNameDiv:
newItemBtn.addEventListener("click", (e) => {
_insertNewItemInput(e, project);
})
const _insertNewItemInput = (e, project) => {
const incompleteTaskList = document.querySelector(".incomplete-task-list");
// this adds a task object to the internal task array
const newTask = controller.addNewTask("Enter name here", project);
// this creates a DOM element for the new task and adds it to the DOM
incompleteTaskList.append(_createTaskElement(newTask));
setTimeout(() => {
const taskIndex = model.taskArray.indexOf(newTask);
const taskNameDiv = document.querySelector(`.task-name[data-task="${taskIndex}"]`);
taskNameDiv.focus();
}, 10);
}
The setTimeout(func, 10) is necessary because the program was trying to focus on the taskNameDiv before it had finished being inserted into the DOM. But on iOS Safari, despite the element having focus, the keyboard doesn’t pop up.
This isn’t a problem on desktop because the keyboard doesn’t need to pop up—the div gets focus, you can start typing. But on mobile, there’s a blue outline indicating the box has focus, but no keyboard. If I click within the focused div, then the keyboard appears.
I’ve scoured StackOverflow answers, but none are quite what I’m looking for:
- This person just wants to achieve focus, which I’ve accomplished
- This one is asking about contentEditable divs in relation to labels
- This question is about
input[type="text"], notdiv[contentEditable]
On Reddit, I’ve searched r/javascript, r/webdev, and r/learnprogramming. I did manage to find this one person with my exact problem from four years ago, but none of the suggestions work for me.
I’ve tried:
- using
rangeto specify where the caret should go, hoping that would force the keyboard up, but I can’t get the caret to show up at all, much less obey like it does when I do the same thing forinput[type="text"]elements - adding
e.preventDefault() - adding
taskNameDiv.blur()beforetaskNameDiv.focus()
But I’m running out of things to try. Any help would be greatly appreciated.
Rendering query string variables in React [duplicate]
I’m trying to display a query string in my React component.
http://localhost:3000/results?s=hello
Does anyone know why this isn’t working?
function Results() {
var query = new URLSearchParams(this.props.location.search);
var greeting = query.get('s')
return (
<div>{greeting}</div>
)
}
export default Results;
When I replace it with the following it works, but I don’t want to hardcode the greeting.
function Results() {
var greeting = 'Hello'
return (
<div>{greeting}</div>
)
}
export default Results;
Thank you
Wait for function to complete before completing the next [duplicate]
How can I make it so Prior Messages are always displayed first (are the first messages)? Sometimes "1. Prior messages" is called last and hence overwrites the joined message "2. Joined". Order needs to be 1. then 2.
// OnLoad fetch Chat
useEffect(() => {
// Load prior messages
const fetchLoadPriorChat = async () => {
try {
const response = await fetch('https://localhost:6351/api/home/loadChat/' + chatId + '/' + threadId)
if (!response.ok) throw Error('Did not recieve expected data')
setFetchError(null)
const chatData = await response.json();
setMessages(chatData.messages);
console.log("1. Prior messages")
} catch (err) {
setFetchError(err.message)
} finally {
setIsLoading(false)
}
}
fetchLoadPriorChat()
// Load joined message
const fetchJoinedMessage = async () => {
try {
const connection = new HubConnectionBuilder()
.withUrl("https://localhost:7168/chat")
.configureLogging(LogLevel.Information)
.build();
// When "JoinRoom" is invoked "RecieveMessage" will be invoked because it contains the method name "RecieveMessage"
connection.on("RecieveMessage", (user, name, text, timestamp) => {
var id = user;
var joinedRoomMessage = { id: id, name: name, text: text, timestamp: timestamp }
// Add joined message to rest of messages
setMessages(messages => [...messages, joinedRoomMessage ]);
console.log("2. Joined message")
});
var user = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
var room = "coding"
await connection.start();
await connection.invoke("JoinRoom", { user, room });
setConnectionId(connection)
} catch (err) {
setFetchError(err.message)
} finally {
setIsLoading(false)
}
}
fetchJoinedMessage()
}, [])
How can I retain the cookies in the response?
const setContext = require('apollo-link-context');
const axios = require('axios')
const req = async () => {
const dotenv = require("dotenv")
dotenv.config()
const res = await axios.post(process.env.URL, {
email: process.env.EMAIL,
password: process.env.PASSWORD}, {
headers: {
'content-type' : 'application/x-www-form-urlencoded'
}
}, {withCredentials: true}
);
console.log(res.headers['set-cookie']);
}
req();
Does anyone know how to retain the cookies in the response? There are two specific cookies in the response I want to save in a variable so I can use for another request.
I have tried reading documentation and using other libraries for requests, but nothing works.
php – Display Events with Form Submit (FullCalendar)
Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. “meeting”)
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=s|$)).*/', '\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I’m missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.
Jest failing one function but not another
I am writing some daily challenges for my coding bootcamp and I am running into an issue on one problem. I wrote a function that combines objects and it works correctly. Here is what the problem prompt is
Prompt: Write a function named mergeObjects that accepts at least two objects as arguments, merges the properties of the second through n objects into the first object, then finally returns the first object. If any objects have the same property key, values from the object(s) later in the arguments list should overwrite earlier values.
Examples:
mergeObjects({}, {a: 1}); //=> {a: 1} (same object as first arg)
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}); //=> {a: 1, b: 2, c: 3, d: 4}
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}, {b: 22, d: 44}); //=> {a: 1, b: 22, c: 3, d: 44
My function
function mergeObjects(...obj) {
let obj1 = {}
obj.forEach(element => {
obj1 = {...obj1, ...element}
});
return obj1
}
Solution function
function mergeObjects1(target, ...objects) {
objects.forEach(function (obj) {
// using ES2015's 'for in' loop
for (var key in obj) {
target[key] = obj[key]
}
})
return target
}
In my eyes these two functions provide the same result. However, when I run my code through the jest test they created it fails on the first test. But the solution they provide, does not fail. The jest test is below.
describe('15-mergeObjects', function () {
it('returns same object', function () {
var obj = {}
expect(mergeObjects(obj, { a: 1 })).toBe(obj)
})
it('adds additional properties', function () {
expect(mergeObjects({ a: 1, b: 2, c: 3 }, { d: 4 })).toEqual({
a: 1,
b: 2,
c: 3,
d: 4
})
})
it('merges props from left to right', function () {
expect(
mergeObjects({ a: 1, b: 2, c: 3 }, { d: 4 }, { b: 22, d: 44 })
).toEqual({ a: 1, b: 22, c: 3, d: 44 })
})
})
describe('15-mergeObjects', function () {
it('returns same object', function () {
var obj = {}
expect(mergeObjects1(obj, { a: 1 })).toBe(obj)
})
it('adds additional properties', function () {
expect(mergeObjects1({ a: 1, b: 2, c: 3 }, { d: 4 })).toEqual({
a: 1,
b: 2,
c: 3,
d: 4
})
})
it('merges props from left to right', function () {
expect(
mergeObjects1({ a: 1, b: 2, c: 3 }, { d: 4 }, { b: 22, d: 44 })
).toEqual({ a: 1, b: 22, c: 3, d: 44 })
})
})
Can anyone provide an explanation as to why the solution function passes while my function does not?
Page showing Blank Screen due to React Router Dom v6
I am building a Music Streaming Application, that works as a streaming services for 4 playlists. The names of these playlists are Metal, Rock, Rap, House. I have created individual files for them named, Metal.js, Rock.js, Rap.js, House.js. These four playlists are nested on my Home.js page.
Question#1:
The part I’m stuck on is routing a button link from Home.js to either of the playlists. I followed a tutorial on how to use react-router-dom, however when I implemented it on my code, I was returned with a blank screen.
What’s wrong with it?
The Code:
Home.js
import React, { Component } from 'react';
import '../components/Home.css';
import {
BrowserRouter as Router,
Routes,
Route,
Link
} from "react-router-dom";
import Rap from './Rap';
import House from './House';
import Metal from './Metal';
import Rock from './Rock';
export default class Home extends Component{
render(){
return(
<Router>
<div>
<h1> Home</h1>
<img src={process.env.PUBLIC_URL + '/things.png'} alt="things" />
<button>
<Link to="/metal">
<button type="button">
Click Me!
</button>
</Link>
</button>
<button>
<Link to="/rap">
<button type="button">
Click Me!
</button>
</Link>
</button>
<button>
<Link to="/rock">
<button type="button">
Click Me!
</button>
</Link>
</button>
<button>
<Link to="/house">
<button type="button">
Click Me!
</button>
</Link>
</button>
</div>
<div>
<Routes>
<Route path="/Metal" element={<Metal/>} />
<Route path="/Rock" element={<Rock />} />
<Route path="/House" element={<House />} />
<Route path="/Rap" element={<Rap />} />
</Routes>
</div>
</Router>
)
}
}
Additionally I will include one of the playlist components(they are all the same).
House.js
import React, { Component } from 'react';
export default class House extends Component{
render(){
return(
<div>
<h1> HOUSE</h1>
</div>
)
}
}
Question#2
I want have a stylish clickable box, instead of a plain button that gets routed to the its respective page. Im trying to code these boxes, and route them to their pages as well :


Any Idea on how I would be able to do it?
I’m new to programming, really appreciate the feedback.
Cypress – How to count Number of Buttons in a Div?
I’m trying to find a way to count the number of buttons within a given div, right now the html looks something like this:
<div class="Button_List"></div>
<div class="Button_Container">
<button class="button1"></button>
<button class="button2"></button>
<button class="button3"></button>
</div>
</div>
My Cypress Assertion looks something like this:
cy
.find('.Button_Container')
.its('length')
.should('eq', 3)
Cypress keeps saying it only find one item though: expected 1 to equal 3
I’m new to Cypress/Automation in general so any help would be appreciated!
Accessing dynamic properties of an Object in React
I’m checking whether there is a placeholder present in the “all” string within alertDetails object so my question is I need to access email,sms,fax property that appears dynamically based on user’s input (the code is a part of an alert box in which an user can choose to send alert via different delivery methods) so I saved all the possible delivery methods in an array and tried like below;
Const delmethod=[“email”,”sms”,”fax”]
for(let i=0;i<delmethod.length;i++)
{
Console.log(alertDetails &&
alertDetails.alertMessage &&
alertDetails.alertMessage[${lang}] &&
alertDetails.alertMessage[${lang}].all
? alertDetails.alertMessage[${lang}][‘${delmethod(i)}’].includes('placeholder')
: false;
}
P.S:the property “all” is fixed it’s just the email fax will be changing based on user’s input, to sum it up I want to return true if “placeholder” exists in any of the strings(all,email,fax,sms) the method I tried just prints the del method array, I’d appreciate any help thanks!
Syntax error insert dimension to complete reference type
Ok so I’m quite new to Java and I don’t know what to do at this point with the error
Google Maps Javascript API geolocation directions
I’m trying to get directions from a users current location to another location where they can decide where to go. This is my code so far where it pulls from a select ID within the HTML page for the origin and destination, but I’m having trouble setting the origin as the users current location. This is from the Google Developers help page as well, I just needed something to start with.
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService
.route({
origin: {
query: document.getElementById("start").value,
},
destination: {
query: document.getElementById("end").value,
},
travelMode: google.maps.TravelMode.WALKING,
})
.then((response) => {
directionsRenderer.setDirections(response);
})
.catch((e) => window.alert("Directions request failed due to " + status));
}
Generic repository typescript / router-controller API
‘im trying to make a generic repository for my api but i’m stuck…
how can i use a type as a string to select the right table ?
export default abstract class GenericRepository<T> {
async getAll(): Promise<T[]> {
try {
const client = await db.connect();
const res = await client.query<T>(`SELECT * FROM rant_${T.toString()}`); // <-- here
client.release();
return res.rows;
} catch (error) {
throw new InternalServerError('ERROR');
}
}
}
MediaRecorder: Record from Microphones and Play audio from Element (music playback)
I like to record my voice with some mp3 music that I choose from the video tag, When I change the src audio element, the new music doesn’t record, MediaRecorder just records the first music, so I like to record all music coming from the video tag src.
let constraintObj = {
audio: 1,
video: 0}
navigator.mediaDevices
.getUserMedia(constraintObj)
.then((mediaStreamObj) => {
let start = document.getElementById("btnStart");
let stop = document.getElementById("btnStop");
let autostop = document.getElementById("autobtnStop");
let playAudio = document.getElementById("pma");
var playAudioStream = playAudio.captureStream();
let audioContext = new AudioContext();
const acsource = audioContext.createMediaElementSource(playAudio);
acsource && acsource.connect(audioContext.destination);
let dest = audioContext.createMediaStreamDestination();
let audioIn_01 = audioContext.createMediaStreamSource(mediaStreamObj);
let audioIn_02 = audioContext.createMediaStreamSource(playAudioStream);
audioIn_01.connect(dest);
audioIn_02 && audioIn_02.connect(dest);
let mediaRecorder = new MediaRecorder(dest.stream);
let chunks = [];
start.addEventListener("click", () => {
mediaRecorder.start();
console.log(mediaRecorder.state);
});
stop.addEventListener("click", () => {
mediaRecorder.stop();
});
autostop.addEventListener("click", () => {
if (mediaRecorder.state !== "inactive") {
mediaRecorder.stop();
}
});
mediaRecorder.ondataavailable = (ev) => {
chunks.push(ev.data);
if (selectedEpisodes !== null && sameDate <= 0) {
let blobFile = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
chunks = [];
const datas = {
name,
episode_id,
record_datetime: record_datetime,
playtime_sec: playtime_sec,
files: blobFile,
};
dispatch(editEpisodeStatus(epSelected_ID, { status: "finished" }));
dispatch(createPodcast(datas));
}
};
mediaRecorder.onstop = () => {
let blobFile = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
chunks = [];
const datas = {
name,
episode_id,
record_datetime: record_datetime,
playtime_sec: playtime_sec,
files: blobFile
};
dispatch(editEpisodeStatus(epSelected_ID, { status: "finished" }));
dispatch(createPodcast(datas));
};
})
.catch((err) => {
console.log("catch startLive", err.name, err.message);
});
Hi, I like to record my voice with some mp3 music that I choose from the video tag, When I change the src audio element, the new music doesn’t record, MediaRecorder just records the first music, so I like to record all music coming from the video tag src.