So I really like programming with HTML5, CSS, and JS. I’m relatively new to it. I was wondering if it is possible to make apps with HTML5, CSS, and JS. If so how could I put a project into app form and what courses would you recommend as I am probably still considered a beginner in JS.
Category: javascript
Category Added in a WPeMatico Campaign
Intersection observer Hook doesn’t work when threshold is set to 1 on google chrome
I am trying to make Intersection observer so I can implement infinity scroll in my react app. I decided to create a hook “useInfinityScroll” which accepts ref as prop, and by using intersection observer with threshold of 1 I wanted to be notified when user is intersecting with that ref. But for some reason when user scrolls to selected element and satisfies threshold requirement still “isIntersecting” is not equal to “true” value. And thats only the case for google chrome on my mac, it works fine with mozilla and with chrome on pc.
Here is my hook
import {useCallback, useEffect, useState} from "react";
import {not} from "ramda";
export function useInfinityScrollObserver(ref) {
let [isVisible, setIsVisible] = useState(false);
const handleIntersection = useCallback(([entry]) => {
if (entry.isIntersecting){
setIsVisible(true)
}else if (not(entry.isIntersecting)){
setIsVisible(false)
}
}, [])
useEffect(() => {
const options = {
threshold: 1
}
// Create the observer, passing in the callback
const observer = new IntersectionObserver(handleIntersection, options);
// If we have a ref value, start observing it
if (ref.current) {
observer.observe(ref.current);
}
// If unmounting, disconnect the observer
return () => {
observer.unobserve(ref.current)
observer.disconnect();
}
}, [ref,handleIntersection]);
return isVisible;
}
Here is component where I use it:
import {useInfinityScrollObserver} from "../../hooks/useInfinityScrollObserver";
import {useEffect, useRef, useState} from "react";
const CountriesSection = () => {
const sectionRef = useRef(null);
const isVisible = useInfinityScrollObserver(sectionRef)
useEffect(() => {
if (isVisible){
console.log("IS VISIBLE")
}
}, [isVisible])
return (
<section ref={sectionRef} className={styles['section-countries']}>
</section>
)
}
export default CountriesSection;
How to send data read from file as response from an express route in NodeJS?
I have a JSON file in local folder with a structure like this.
{
license: "abcd",
name: "abcd",
data: [
Array of JSON Objects ....
]
}
I want to access the data array in the Object and send it as response from express route
This is what I tried.
import express from "express";
import fs from "fs";
import bodyParser from "body-parser";
var app = express();
app.use(bodyParser.json());
var fileData: string = fs.readFileSync("path to json file", { encoding: 'utf-8' });
var jsonData = JSON.parse(fileData).data;
console.log(jsonData);
app.get("/getJsonData", (err, res) => {
if (err)
throw err;
res.send(JSON.stringify(jsonData));
});
app.listen("3001", () => console.log("listening at 3001"));
It shows correct json when I log it outside the express route function, but inside the function the response is [object Object] with status code of 500 (Internal Server Error).
I tried the asynchronous method also
var app = express();
app.use(bodyParser.json());
app.get("/getJsonData", (err, res) => {
if (err)
throw err;
fs.readFile("path to json file", (fileErr, result) => {
if(fileErr) throw fileErr;
var jsonData = JSON.parse(result.toString()).data;
res.json(jsonData);
});
});
but I get the same response as [object Object] and status code 500.
I tried res.send(JSON.stringify(jsonData)) but no use.
How can I send the json data that I get from file to frontend using Express??
btw I am using TypeScript for this.
How to fetch data just on the first load of component
I want to know how to fetch data just on the first load of component and not on every reload.
I hope that is making sense.
so something like that will be calling in every load
useEffect(() => getData(), []);
For example : I want to fetch the data for the pieces when the user click on pieces section not before. see the picture.
enter image description here
Select drop down value not getting received in an email while other fields are, using JS and php in an email form
Hi I am using the following html, JS and php to send an email form. All values are being received in the mail except select option drop down value. I want people and roomtype values to be mailed along with other data.
<form name="sentMessage" id="bookingForm">
<div class="row">
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Name</label>
<input type="text" name="message-name" id="name" class="form-control mb-30" placeholder="Your Name" required data-validation-required-message="Please enter your name.">
</div>
</div>
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Email</label>
<input type="email" name="message-email" id="email" class="form-control mb-30" placeholder="Your Email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Phone</label>
<input type="number" name="message-phone" id="phone" class="form-control mb-30" placeholder="Your Phone" required data-validation-required-message="Please enter your phone number.">
</div>
</div>
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Arrival Date</label>
<input type="date" name="message-arrival" id="arrival" class="form-control mb-30" placeholder="Arrival Date *" required data-validation-required-message="Please enter arrival date." value="<?php echo date('Y-m-d'); ?>">
</div>
</div>
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Departure Date</label>
<input type="date" name="message-departure" id="departure" class="form-control mb-30" placeholder="Departure Date *" required data-validation-required-message="Please enter arrival date." value="<?php echo date('Y-m-d'); ?>">
</div>
</div>
<div class="col-12 col-lg-4 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>No. of People</label>
<select class="form-control" id="people" name="people" required data-validation-required-message="Please select number of people.">
<option value="" disabled selected>Select no.s of people *</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</div>
</div>
<div class="col-12 col-lg-6 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<label>Room/ Suite Type</label>
<select class="form-control" name="roomtype" id="roomtype" required data-validation-required-message="Please select type of room/ suite.">
<option value="" disabled selected>Select Room/Suite *</option>
<option value="1"> Family Suite-I </option>
<option value="2"> Family Suite-II </option>
<option value="3"> Double Bed Room </option>
</select>
</div>
</div>
<div class="col-12 wow fadeInUp" data-wow-delay="100ms">
<div class="form-group">
<br/><label>Comments</label>
<textarea name="message" id="message" class="form-control mb-30" placeholder="Your Message" required data-validation-required-message="Please enter a message."></textarea>
</div>
</div>
<div class="col-12 text-center wow fadeInUp" data-wow-delay="100ms">
<div id="success"></div><!--Required for Mail Sent-->
<button type="submit" class="btn roberto-btn mt-15">Send Message</button>
</div>
</div>
</form>
This is the Java script.
// Booking Form Scripts
$(function() {
$("#bookingForm input,#bookingForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var arrival = $("input#arrival").val();
var departure = $("input#departure").val();
var people = $("input#people").val();
var roomtype = $("input#roomtype").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/bookmail/mail/book.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
arrival: arrival,
departure: departure,
people: people,
roomtype: roomtype,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. Will Contact you Shortly. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#bookingForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#bookingForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle="tab"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
This is the PHP code which I am using with the html and js to send the data in email
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['arrival']) ||
empty($_POST['departure']) ||
//empty($_POST['people']) ||
//empty($_POST['roomtype']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$emailadd = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$arrival = strip_tags(htmlspecialchars($_POST['arrival']));
$departure = strip_tags(htmlspecialchars($_POST['departure']));
$people = strip_tags(htmlspecialchars($_POST['people']));
$roomtype = strip_tags(htmlspecialchars($_POST['roomtype']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - This is where the form will send a message to.
$email_subject = "Website Booking Form: $name";
$email_body = "You have received a new message from your website contact form.nn"."Here are the details:nnName: $namennEmail: $emailaddnnPhone: $phonennArrival: $arrivalnnDeparture: $departurennPeople: $peoplennRoomtype: $roomtypennMessage: $message";
$headers = "From: noreplyn"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
How to set event listenet for ‘Enter’ key in textarea with js [duplicate]
I am making a terminal themed website
so far I tried this
textArea.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
runCommand(textArea.value);
textArea.value = "";
}
})
but after the running one command Textarea cursor moves to a new line and switch case stops working
how to reset the Textarea totally or use enter key without moving to new line?
How to hide deleted text backgound of monaco editor?
Prevent change of dropdown options when underlying data changes
With the code below:
<!DOCTYPE html>
<html>
<body>
<head>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
</body>
<script type="text/babel">
const api = {
data: [
{
id: 1, party: 'Zuckerberg', news: [
{id: 1, headline: 'Zuckerberg news1'},
{id: 2, headline: 'Zuckerberg news2'},
]
},
{
id: 2, party: 'Musk', news: [
{id: 1, headline: 'Musk news1'},
{id: 2, headline: 'Musk news2'},
]
},
]
}
const App = () => {
const [data, setData] = React.useState([])
React.useEffect(() => setData(api.data), [])
const handleSelectChange = (e) => {
const name = e.target.value
setData(prev => prev.filter(datum => datum.party === name))
}
return (
<div>
<select
onChange={handleSelectChange}>
{data.map(datum => <option key={datum.id}>{datum.party}</option>)}
</select>
{data.map(
datum =>
datum.news.map(newsItem =>
<div key={newsItem.id}>{newsItem.headline}</div>
)
)}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
</script>
</html>
how can I prevent the reduction of dropdown options upon dropdown change, preferably without changing the api.data structure?
I basically need this dropdown to be refreshed only when api.data returns new data.
Is it possibly while keeping only single state (data)?
How I can Update only relevant data with this Update Controller?
Update Controller
exports.UpdatePanelMembers = (req, res) => {
const { panelId } = req.params;
if (panelId) {
Panel.findOneAndUpdate(
{ _id: panelId },
{
panelMembers: {
member1: {
memberId: req.body.panelMembers.member1.memberId,
fullName: req.body.panelMembers.member1.fullName,
username: req.body.panelMembers.member1.username,
},
member2: {
memberId: req.body.panelMembers.member2.memberId,
fullName: req.body.panelMembers.member2.fullName,
username: req.body.panelMembers.member2.username,
},
member3: {
memberId: req.body.panelMembers.member3.memberId,
fullName: req.body.panelMembers.member3.fullName,
username: req.body.panelMembers.member3.username,
},
},
}
).exec((error, result) => {
if (error) return res.status(400).json({ error });
if (result) {
res.status(202).json({ result });
}
});
}
};
In this code, if I update member1 details only, other data will be erased. So I want to update only relevant data like this postman JSON.
Postmen JSON Code
{
"panelMembers": {
"member1": {
"username":"john.j",
"fullName":"John Jade",
"memberId":"member123"
}
}
}
How to use regex to match an IPFS URL?
I have the following IPFS URL.
https://ipfs.moralis.io:2053/ipfs/QmPQeMz2vzeLin5HcNYinVoSggPsaXh5QiKDBFtxMREgLf/images/0000000000000000000000000000000000000000000000000000000000000001.png
I want to use regex to match this file, but instead of writing the full URL, I want to just match something like https*00000001.png.
The problem is that when I use
paddedHex = '00000001';
let tmpSearchQuery = `https*${paddedHex}.png`;
It doesn’t really match anything. Why?
how to display different colors on each column of a row using ngClass in agular?
I have 4 rows, each row contains 3 cards.
I am fetching information for these cards from db then rendering them using ngfor in html.
The problem is I want each of card of a row to show different color.
Example:->
ROW 1:
BLUECARD | WHITECARD | REDCARD
ROW 2:
BLUECARD | WHITECARD | REDCARD
as of now I able to do for two colors but how can I make it for 3 colors as I stated in example.
<div *ngFor="let r of rates; let i=index;">
<div class="box" [ngClass]="i % 2 == 0 ? 'BLUECARD' : 'REDCARD'">
<!-- card contents -->
</div>
</div>
As you can see I am able to show 2 colors alternatively but how can I show 3 colors instead?
Remove /#/ from link?
I’m trying to write a single page application and I’m using this class for routing:
class code
then I add routes
export const routes = [
{
path: /task-list/,
callback: () => {
console.log('callback');
}
}
];
export const router = new Router({
root: '/task-list',
mode: 'hash',
routes
});
I expect that when loading the site, I will get a link localhost:3000/task-list, but for some reason I get localhost:3000/#/task-list, I can’t figure out how to remove this /#/
Problem with Jquery in django project template
JavaScript OpenLayers: add attributes to a drawn feature (point, polygon, circle)
I want to create a webapp in which the user can draw features on a raster and add attributes to it. Sadly, I am a bit of a newbie.
Using OpenLayers and a GeoServer, I succesfully managed to display a raster on the OpenLayers. Furthermore, I also managed to create a draw layer, in which the user can choose between options: point, circle and polygon.
Now I only want to add the option to add attributes to the feature that has been drawn. (And subsequently for example, click afterwards on it to see said attributes).
Creating the map (‘…’ for working stuff that I don’t necessarily want to disclose):
var mapView = new ol.View ({
center: ol.proj.fromLonLat([..., ...]),
zoom: ...,
});
var map = new ol.Map ({
target: 'map',
view: mapView,
})
var noneTile = new ol.layer.Tile({
title: 'None',
type: 'base',
visible: false
});
var osmTile = new ol.layer.Tile ({
title: 'Open Street Map',
visible: true,
type: 'base',
source: new ol.source.OSM()
});
// map.addLayer(osmTile)
var baseGroup = new ol.layer.Group({
title: 'Base Maps',
fold: true,
layers: [osmTile, noneTile]
});
map.addLayer(baseGroup)
var Raster = new ol.layer.Tile({
title: 'Raster',
source: new ol.source.TileWMS({
url: ...,
params: {'LAYERS':..., 'TILED': true},
serverType: 'geoserver',
visible: true
})
});
// map.addLayer(Raster);
So this works, now I add the draw function:
// Add draw layer
const source = new ol.source.Vector({wrapX: false});
const drawLayer = new ol.layer.Vector({
source: source,
});
const typeSelect = document.getElementById('type');
let draw; // global so we can remove it later
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value,
});
map.addInteraction(draw);
}
}
/**
* Handle change event.
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
document.getElementById('undo').addEventListener('click', function () {
draw.removeLastPoint();
});
addInteraction();
I think these are the most important parts of the code. Now, this gives me nicely the map with the raster on it and the ability to draw features. But I cannot add attributes yet, and I am stuck there.
What I tried (following: Assign Id / name attribute for uniquely identifying drawn polygon):
let draw; // global so we can remove it later
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value,
});
map.addInteraction(draw);
draw.on('drawend', function(evt){
var feature = evt.feature;
feature.setId(some_uniq_id);
//do you want to set other properties?
feature.setProperties({
name: 'some_name'
});
});
}
}
But this does not work for me. At least, I cannot see the id and attributes and the drawn polygon removes from itself.
What am I doing wrong or what do I need to do/add?
Making neat variable lists from multiple arrays to use as ‘clean’ arguments in a later function (javascript)
okay I’m pretty noob but have been enjoying the recursive-ness of js
I’m [hopefully] making expandable info boxes that operate independently.
Instead of making 5 different animation/onClick() behaviours for each one, I figure I’ll name all the elements to a specification i made up (because sadly i’m in wix/velo and I need to refer to them as $(‘#element’), etc) and then generate an object that contains the strings to plug in as arguments.
After some mind blowing moments, I was successful (yes I’m dumb).
here is my final output that gives me each category and their array with the strings
heres the code if the image didn’t load:
let parts = ["Win')", "List')", "Text')", "ArL')", "ArR')"];
let cats = ["$w('fam", "$w('mwl", "$w('aes", "$w('hrm"];
function merger(c, p) {
let result = [];
let i;
for (i = 0; i != p.length; i++) result[i] = c + p[i];
return result;
}
const final = {
fam: merger(cats[0], parts),
mwl: merger(cats[1], parts),
aes: merger(cats[2], parts),
hrm: merger(cats[3], parts)
};
//object made with category: [string1, string2,...] for each
console.log (final);
I know {final} could be improved but that brings me to my actual question(s).
My animation/onClick() function (not pictured, happens after); if it was to run independently for each category, it needs the strings in the array of each category, which thankfully I managed to generate.
However I’d rather not refer to them literally from the array like categoryStr[0] because then I’d still kinda have to copy/paste the function [i] times for each category, no?
So how can I turn all the strings in each array of this object I’ve made into objects themselves, so that way the functions I do later only need to refer to a single object like ‘for each {category}Str.Text” instead of for famStr[i], for hrmStr[i], etc.
Like later I’d hope to make a for loop or something that executes my future “interactiveFunction(category)” for all my categories using each of their variable lists in a tidy way, but hitting that goal is just beyond me, I figure I can do that if the variable list is clean and I just reference a neat object like ‘category.param’ instead of ‘category[2]’. idk data types and valid references haven’t quite settled for me yet. I figure a first post would usually be embarrassing but hey I’m drunk, head-scratching, and an outside perspective from StackOverflow peeps would really help me rn along with all the docs i’ve been reading. Maybe it’s time to hire a tutor…

