how to embed an **adblock **in a specific html **iframe **element
that iframe providing some video but i down want see ads in its element.
how to embed any **adblock **in a specific html **iframe **element. please help. App is building in react.js
Category: javascript
Category Added in a WPeMatico Campaign
Icant use high chart in AdminLTE
I am using version 3 of AdminLTE and I want to use high chart in it, when I want to use pie charts, the labels are white and I could not change its style with css style and different methods. Is there a problem with the js version? How is the problem solved?
I tried different ways to change the style of the label, but I didn’t get an answer
How to change text in input area
I’m trying to make a temperature converter. Right now I’ve started at getting from Celsius to Fahrenheit. My conversion function works correctly what doesn’t is putting Fahrenheit value of the Celsius degree into the Fahrenheit area right now it just enters NaN.
This is what I currently have
let convert = document.getElementById(“convert”)
convert.addEventListener(“click”,function(){
let cel = document.getElementById(“cel”)
let newTemp = convertCtoF(parseFloat(cel));
document.getElementById(“fah”).value=newTemp;
}
Why I’m getting and error with async in mock factory on Vitest?
I’m learning to use Vitest and I found a weird behavior. I have this code:
import { expect, test, vi } from 'vitest';
import { main, mainB } from './src/main.js';
import x from './src/export-default-index.js';
vi.mock('./src/A', async () => ({
...(await vi.importActual('./src/A.js')),
funcA: () => 'mockedA'
}));
vi.mock('./src/B.js', async () => ({
...(await vi.importActual('./src/B.js')),
funcB: () => 'mockedB'
}));
vi.mock('./src/export-default.js');
test('can import actual inside mock factory', () => {
expect(main()).toBe('mockedA');
});
test('can import in top level and inside mock factory', () => {
expect(mainB()).toBe('mockedB');
});
test('can mock a circular dependency', () => {
expect(x()).toBe(undefined);
});
I took this code from one of the examples they had in the Github repository.
https://github.com/vitest-dev/vitest/blob/main/examples/mocks/test/circular.spec.ts
When I run the test in the Vitest repository (I downloaded it and ran it on my machine) works ok, but then I move this class and all the other classes that appeared in the code to my project and if I try to run it I’m getting this error in the vi.mock method:
Cannot access '__vi_import_0__' before initialization
If I remove the async and the await works ok, but in every example I’ve seen and in the documentation (Vi.mock) they always use the async in the mock factory. Does anyone know why is not working async for me?
Semver LRU is not a constructor in yarn workspace
I have a project that I migrated from a standalone npm package to a yarn package in a workspace. My config is working correctly for building and type-checking, but when I try to run yarn test, my test suite fails with
TypeError: LRU is not a constructor
at Object.<anonymous> (../node_modules/semver/classes/range.js:202:15)
at Object.<anonymous> (../node_modules/semver/classes/comparator.js:141:15)
at Object.<anonymous> (../node_modules/semver/index.js:29:20)
at _jestSnapshot (../node_modules/@jest/expect/build/index.js:15:16)
at createJestExpect (../node_modules/@jest/expect/build/index.js:30:28)
at Object.<anonymous> (../node_modules/@jest/expect/build/index.js:39:20)
It seems like its an issue with versioning or configuration for the semver or lru-cache packages, but I’m unable to resolve it. I’ve run yarn add semver --dev and yarn add lru-cache --dev to see if I can resolve the issue, but it is persisting.
Here is the root level package.json:
{
// name, version, repository, author, and license omitted
"private": true,
"workspaces": [
"webapp",
],
"packageManager": "[email protected]",
"dependencies": {
"@jest/expect": "^29.7.0",
"semver": "^7.6.0"
}
}
And then in webapp/package.json
{
...,
"scripts": {
...
"test": "jest --runInBand",
},
"dependencies": {
...
},
"devDependencies": {
...,
"lru-cache": "^10.2.0",
},
"packageManager": "[email protected]"
}
There is no tsconfig or jest config at the root level. In the webapp directory, the config looks like:
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx",],
"exclude": ["node_modules", "dist"],
"ts-auto-mock": {
"createMock": {
"properties": "fake"
}
}
}
jest.config.js
const nextJest = require("next/jest");
const createJestConfig = nextJest({ dir: "./" });
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = createJestConfig({
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
modulePathIgnorePatterns: ["<rootDir>/.*/__mocks__"],
preset: "ts-jest",
testEnvironment: "node",
moduleDirectories: [
"<rootDir>/node_modules",
"<rootDir>/../node_modules",
"<rootDir>/src",
],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
transform: {
"^.+\.[tj]sx?$": "@swc/jest",
},
workerIdleMemoryLimit: "1024MB",
testMatch: ["**/tests/**/test_*.(ts|tsx|js)"],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
setupFiles: ["<rootDir>/tests/setup.ts"],
setupFilesAfterEnv: ["<rootDir>/tests/setupAfterEnv.ts"],
cacheDirectory: ".jest/cache",
cache: true,
verbose: true,
});
Before, the root-level node_modules was not being recognized, but now it is. However, i am unable to resolve the issue regarding LRU not being a constructor.
trouble changing span text size attributes on Reddit comments
I cannot seem to change the upvote count in the comment section of Reddit to display 0 or none for example. First time using JS go easy. Testing this in Firefox.
const commentElement = document.querySelectorAll('span.p-0.text-12');
commentElement.forEach(commentElement => {
commentElement.style.fontSize = '0';
});
I have tried looping through the spans and directly changing the size. No dice. Let me know if this is more trivial in JQuery. Thanks!
Getting a 400 error when exchanging authorization code for access token in Spotify API integration
I’m working on integrating Spotify API into my web application using the Authorization Code with PKCE Flow. I’ve followed the documentation provided by Spotify, but I’m encountering a 400 error when trying to exchange the authorization code for an access token.
Here’s a summary of what I’ve done:
- Implemented the PKCE extension to generate a code verifier and code challenge.
- Redirected the user to Spotify’s authorization page with the appropriate parameters, including the code challenge.
- After the user grants permission, received the authorization code in the callback URL.
- Attempted to exchange the authorization code for an access token using a POST request to Spotify’s token endpoint.
However, the POST request to exchange the authorization code for an access token is failing with a 400 error. I’ve double-checked the parameters, including client_id, grant_type, redirect_uri, code_verifier, and code, and they all seem to be correct.
Here’s a simplified version of the code I’m using:
const clientId = [YOUR_CLIENT_ID];
const redirectUri = 'http://localhost:3000';
const generateAuthCode = async () => {
// Generate code verifier
const codeVerifier = 'generated_code_verifier';
// Redirect user to Spotify authorization page
const authUrl = 'https://accounts.spotify.com/authorize';
const params = {
response_type: 'code',
client_id: clientId,
scope: 'playlist-modify-public playlist-modify-private',
code_challenge_method: 'S256',
code_challenge: 'generated_code_challenge',
redirect_uri: redirectUri,
};
const queryString = new URLSearchParams(params).toString();
window.location.href = `${authUrl}?${queryString}`;
};
const generateAccessToken = async (code, setUserInfo) => {
// Exchange authorization code for access token
const url = 'https://accounts.spotify.com/api/token';
const payload = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: 'stored_code_verifier',
}),
};
try {
const response = await fetch(url, payload);
const responseData = await response.json();
setUserInfo((prevInfo) => ({
api_key: responseData.access_token,
userId: prevInfo.userId,
}));
} catch (error) {
console.log('Error:', error);
}
};
export { generateAuthCode, generateAccessToken };
I’ve also logged the response from the server, but it doesn’t provide much information beyond the 400 status code.
Any insights or suggestions on what might be causing this issue would be greatly appreciated. Thank you!
keep existing values on form submit, but reset on form exit?
I have an apps script web form where I want to make sure the supervisor and substation dropdowns maintain their values when an agent is in the form submitting multiple entries. Once the exit the form, I’d like to reset all dropdowns and text boxes.
// Function to save submitted values to local storage
function saveSubmittedValues() {
var supervisor = document.getElementById("supervisor").value;
var substation = document.getElementById("substation").value;
// Save submitted values to local storage
localStorage.setItem("supervisor", supervisor);
localStorage.setItem("substation", substation);
}
// Function to pre-fill dropdowns with saved values from local storage
function prefillDropdowns() {
// Retrieve saved values from local storage
var supervisor = localStorage.getItem("supervisor");
var substation = localStorage.getItem("substation");
// Pre-fill supervisor dropdown
if (supervisor) {
document.getElementById("supervisor").value = supervisor;
}
// Pre-fill substation dropdown
if (substation) {
document.getElementById("substation").value = substation;
// Trigger the onchange event of substation dropdown to populate parcels
getParcels(substation);
}
}
// Call the setDefaultDate function when the page is loaded
window.onload = function() {
setDefaultDate();
prefillDropdowns();
};
rest of html/javascript code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Daily Contact Form </title>
<style>
/* Your CSS styles here */
body {
font-size: 15px;
background-color: #f0f8ff;
font-family: Arial, sans-serif; /* Light blue background color */
}
.container {
width: 50%;
margin: 0 auto; /* Center the container horizontally */
text-align: center; /* Center the content inside the container */
padding-top: 20px; /* Add space at the top */
}
h1 {
margin-top: 20px; /* Add space between header image and header text */
font-size: 20px;
}
select {
width: 50%; /* Set the width of dropdown menus to fill the container */
font-size: 12px; /* Set font size for dropdown values */
text-align-last: center; /* Align dropdown selections in the middle */
}
/* Additional styling to center-align dropdown selections */
option {
text-align: center;
}
textarea {
height: 100px;
width: 250px;
font-size: 12px;
width: 100%; /* Set font size for textarea */
}
input[type="submit"] {
font-size: 12px; /* Set font size for submit button */
}
.submit-message {
color: red;
font-size: 12px;
}
.landowner-info {
float: center;
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
width: 100%; /* Extend size of landowner info box */
}
</style>
<script src="https://apis.google.com/js/api.js"></script>
<script>
// Function to set the default date to today's date
function setDefaultDate() {
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1; // Months are zero indexed
var year = today.getFullYear();
// Format the date as YYYY-MM-DD for the input field
var formattedDate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
// Set the default value of the date picker input field directly
var datePicker = document.getElementById("datePicker");
datePicker.setAttribute("value", formattedDate);
// Set the value of the text box to the same date
datePicker.value = formattedDate;
}
function updateMaxStatusAndLandownerInfo(parcelId) {
updateMaxStatusForParcel(parcelId); // Call updateMaxStatusForParcel with the selected Parcel ID
getLandownerInfo(parcelId); // Call getLandownerInfo with the selected Parcel ID
}
function updateParcelInfo(landowner) {
// Trigger search in "Raw Data" worksheet for landowner value
google.script.run.withSuccessHandler(function(parcelIds) {
var parcelIdDropdown = document.getElementById("parcelId");
parcelIdDropdown.innerHTML = "";
var option = document.createElement("option");
option.value = "";
option.text = "";
parcelIdDropdown.appendChild(option);
// Populate Parcel ID dropdown with matching rows from columns U3:U
parcelIds.forEach(function(parcelId) {
var option = document.createElement("option");
option.value = parcelId;
option.text = parcelId;
parcelIdDropdown.appendChild(option);
});
}).getParcelIdsByLandowner(landowner); // Call server function to get matching parcel IDs
}
function getLandownerInfo(parcel) {
google.script.run.withSuccessHandler(function(landownerInfo) {
document.getElementById("landowner-info-content").innerText = landownerInfo;
}).getLandownerInfo(parcel);
}
function getParcels(substation) {
google.script.run.withSuccessHandler(function(parcels) {
var parcelDropdown = document.getElementById("parcel");
parcelDropdown.innerHTML = "";
var option = document.createElement("option");
option.value = "";
option.text = "";
parcelDropdown.appendChild(option);
// Sort the parcel options alphabetically
parcels.sort().forEach(function(parcel) {
var option = document.createElement("option");
option.value = parcel;
option.text = parcel;
parcelDropdown.appendChild(option);
});
// Update max status immediately after selecting parcel
var selectedParcel = parcelDropdown.value;
updateParcelInfo(selectedParcel);
}).getParcels(substation);
}
// Inside the updateMaxStatusForParcel function, where the status dropdown is being populated
function updateMaxStatusForParcel(parcel) {
google.script.run.withSuccessHandler(function(maxStatus) {
var statusDropdown = document.getElementById("status");
statusDropdown.innerHTML = ""; // Clear previous options
// Define status options in the desired order
var statusOptions = ["", "Assigned to Agent", "Outreach", "Negotiating", "Pledged", "Signed", "Dropped"];
// Add options to the dropdown in the defined order
statusOptions.forEach(function(status) {
var option = document.createElement("option");
option.value = status;
option.text = status;
if (status === maxStatus) {
option.selected = true; // Select the option if it matches the max status
}
statusDropdown.appendChild(option);
});
}).getMaxStatusForParcel(parcel);
}
// Function to save submitted values to local storage
function saveSubmittedValues() {
var supervisor = document.getElementById("supervisor").value;
var substation = document.getElementById("substation").value;
// Save submitted values to local storage
localStorage.setItem("supervisor", supervisor);
localStorage.setItem("substation", substation);
}
// Function to pre-fill dropdowns with saved values from local storage
function prefillDropdowns() {
// Retrieve saved values from local storage
var supervisor = localStorage.getItem("supervisor");
var substation = localStorage.getItem("substation");
// Pre-fill supervisor dropdown
if (supervisor) {
document.getElementById("supervisor").value = supervisor;
}
// Pre-fill substation dropdown
if (substation) {
document.getElementById("substation").value = substation;
// Trigger the onchange event of substation dropdown to populate parcels
getParcels(substation);
}
}
// Call the setDefaultDate function when the page is loaded
window.onload = function() {
setDefaultDate();
prefillDropdowns();
};
function validateForm() {
var isValid = true;
var supervisor = document.getElementById("supervisor").value;
var substation = document.getElementById("substation").value;
var parcel = document.getElementById("parcel").value;
var parcelId = document.getElementById("parcelId").value;
var status = document.getElementById("status").value;
var date = document.getElementById("datePicker").value;
var comment = document.getElementById("comment").value;
// Check if any field is null or blank
if (!supervisor || !substation || !parcel || !parcelId || !status || !date || !comment) {
document.getElementById("submit-message").innerText = "All fields must be filled.";
return false; // Prevent form submission
}
// Save submitted values to local storage
saveSubmittedValues();
// Disable form submit button to prevent resubmission
document.getElementById("submit-button").disabled = true;
return true; // Allow form submission
}
// Prevent form resubmission popup on page reload
if (window.history.replaceState) {
window.addEventListener("beforeunload", function () {
window.history.replaceState(null, null, window.location.href);
});
}
</script>
</head>
<body>
<div class="container">
<img src="https://i.imgur.com/16QsZja.png" alt="Header Image" style="width: 100%; max-width: 200px;">
<h1>Daily Contact Form</h1>
<form method="post" action="<?= getUrl() ?>" onsubmit="return validateForm()">
<label>Land Agent</label><br>
<select name="supervisor" id="supervisor">
<option value=""></option>
<option value="Dan">Dan</option>
<option value="Ian">Ian</option>
<option value="Parker">Parker</option>
</select><br><br>
<label>Substation</label><br>
<select name="substation" id="substation" onchange="getParcels(this.value)">
<option value=""></option>
<? var subs = getDistinctSubstations(); ?>
<? subs.sort().forEach(function(sub) { ?>
<option value="<?= sub ?>"><?= sub ?></option>
<? }); ?>
</select><br><br>
<label>Landowner</label><br>
<select name="landowner" id="parcel" onchange="updateParcelInfo(this.value)">
<!-- Parcel dropdown will be populated dynamically -->
</select><br><br>
<label>Parcel ID</label><br>
<select name="parcelId" id="parcelId" onchange="updateMaxStatusAndLandownerInfo(this.value)">
<!-- Parcel ID dropdown will be populated dynamically -->
</select><br><br>
<label>Status</label><br>
<select name="status" id="status">
<option value=""></option>
<option value="Assigned to Agent">Passed to Agent</option>
<option value="Outreach">Outreach</option>
<option value="Negotiating">Negotiating</option>
<option value="Pledged">Pledged</option>
<option value="Signed">Signed</option>
<option value="Denied">Denied</option>
</select><br><br>
<label for="date">Date</label><br>
<input type="date" name="date" id="datePicker"><br><br>
<label>Comment</label><br>
<textarea name="comment" id="comment"></textarea><br><br>
<input type="submit" name="submitButton" id="submit-button" value="Submit" />
<span id="submit-message" class="submit-message"></span>
</form>
<div class="landowner-info">
<h2>Landowner Info</h2>
<p id="landowner-info-content"></p> <!-- Display landowner information -->
</div>
</div>
</body>
</html>
is there an easy way to do this?
Type ‘string | undefined’ is not assignable to type ‘Matcher | Matcher[] | undefined’
so I’m trying to use shadcn’s calendar for gathering date in my form (react-hook-form + zod) but I have a warning on typescript.
Type ‘string | undefined’ is not assignable to type ‘Matcher |
Matcher[] | undefined’. Type ‘string’ is not assignable to type
‘Matcher | Matcher[] | undefined’.ts(2322)
This is my react-hook-form
const form = useForm<Inputs>({
resolver: zodResolver(formSchemaData),
defaultValues: {
...// other code
dryRunDate: "",
},
});
schema.ts
const formSchemaData = z.object({
dryRunDate: z.string().optional(),
})
Form.ts
<FormField
control={form.control}
name="dryRunDate"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Date of birth</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant={"outline"}
className={cn(
"w-[240px] pl-3 text-left font-normal",
!field.value && "text-muted-foreground"
)}
>
{field.value ? (
format(field.value, "PPP")
) : (
<span>Pick a date</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
{/* Customized Calendar */}
<Calendar
mode="single"
selected={field.value}
onSelect={field.onChange}
initialFocus
/>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>;
Render MathJax within span dimension
I am programmatically creating HTML tags to display LaTeX formulas using MathJax. It seems that the formula is being rendered after the dimension of the <span> tag has been calculated. I want to ensure that the formula is rendered within the span boundaries. What is the fix I kindly ask!?

script.js
formula = "${{{{{{x^2}^2}^2}^2}^2}^2}^2$"
question_div = document.createElement("div");
question_div.setAttribute("id", "q1");
let input = document.createElement("input");
input.name = "a1";
input.id = "a1";
input.type = "radio";
let label = document.createElement("label");
let span_label = document.createElement("span");
span_label.setAttribute("class", "my-span");
span_label.innerText = formula;
label.appendChild(input);
label.appendChild(span_label);
question_div.appendChild(label);
document.body.appendChild(question_div);
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\(', '\)']]
}
};
</script>
<script id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
styles.css
label {
border: 1px solid rgb(199, 199, 199);
margin: 5px;
padding: 4px;
cursor: pointer;
}
div{
padding-top:8px;
padding-bottom:8px;
}
.my-span{
padding-left:8px;
}
How do I change the webcam of a python file by using Flask?
I am working on a face recognition project that sends gen_frame() to video_feed to be rendered in my html file. However, I cannot find the right way to send the localstorage to the Flask. Anyone have some suggestions how I can change the webcam with localstorage?
Here is the python attendance_taker.py which contain the gen_frame method:
`def gen_frame():
cap = cv2.VideoCapture(0) # This is what I want to change using localstorage
face_recognizer = Face_Recognizer()
while True:
success, frame = cap.read()
if not success:
break
face_recognizer.process(frame)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--framern'
b'Content-Type: image/jpegrnrn' + frame + b'rn')`
Here is the javascript code:
`window.addEventListener(“DOMContentLoaded”, function () {
var webcamSelect = document.getElementById(“webcamSelect”);
webcamSelect.addEventListener("change", function () {
var selectedWebcamIndex = webcamSelect.selectedIndex;
localStorage.setItem("selectedWebcamIndex", selectedWebcamIndex);
});
navigator.mediaDevices
.enumerateDevices()
.then((devices) => {
var videoDevices = devices.filter(
(device) => device.kind === "videoinput",
);
videoDevices.forEach((device, index) => {
var option = document.createElement("option");
option.value = index;
option.text = device.label || `Webcam ${index + 1}`;
webcamSelect.appendChild(option);
});
var selectedWebcamIndex = localStorage.getItem(
"selectedWebcamIndex",
);
if (selectedWebcamIndex) {
webcamSelect.selectedIndex = selectedWebcamIndex;
}
})
.catch((error) => {
console.error("Error enumerating devices:", error);
});
});
`
app.py:
@app.route('/video_feed') def video_feed(): return Response(gen_frame(), mimetype='multipart/x-mixed-replace; boundary=frame')
I tried using ajax from jquery, but is not working.
positioning a div using javascipt
my purpose here was aling div with problem class to warning icon, regarless what is the size of the page at the moment it will allways follow the error icon and pop-up (it will normally be hidden) right under it under certain conditions, ı first tried using flex while problem box was inside div with warning class, ı failed, now ı though ı could align it with javascript using getBoundingClientRect but ı came accros a ploblem while trying to align it horizontally, ı need your help, if you can help me solve the problem at hand or show me another way of getting effect ı want ı will be gratefull. have a good day
const error = document.querySelector(".error");
const problem = document.querySelector(".problem");
const button = document.querySelector(".button");
const warning = document.querySelector(".warning");
window.addEventListener("resize", errorPositioning);
function errorPositioning() {
const errorRect = error.getBoundingClientRect();
const warningRect = warning.getBoundingClientRect();
console.log(warningRect);
problem.style.display = "block";
problem.style.left = `${warningRect.left}px`;
problem.style.top = `${errorRect.top - errorRect.top + 20}px`;
}
errorPositioning();
/*
function positionErrorMessage() {
const errorIcon = document.querySelector(".error");
const errorMessage = document.querySelector(".problem");
const iconRect = errorIcon.getBoundingClientRect();
const iconBottom = iconRect.bottom;
const iconLeft = iconRect.left + iconRect.width / 2;
errorMessage.style.display = "block";
errorMessage.style.top = `-${iconBottom}px`;
errorMessage.style.left = `${iconLeft}px`;
}
// Initial positioning when the page loads
positionErrorMessage();
/*error.addEventListener("click", (e) => {
button.classList.toggle("width");
error.classList.toggle("position");
/* error.classList.toggle("asd");
;
if (!e.target.classList.contains("position")) {
problem.classList.remove("hidden");
}
console.log("oldu");
console.log(e);
});
window.addEventListener("click", (e) => {
console.log(e.target);
if (
e.target.classList.contains("error") &&
!e.target.classList.contains("position")
) {
console.log("dogru");
problem.classList.remove("hidden");
} else {
console.log("yanlış");
problem.classList.add("hidden");
error.classList.add("position");
}
});
*/
* {
margin: 0;
padding: 0;
font-family: "Josefin Sans", sans-serif;
}
body {
height: 100vh;
}
.container {
display: flex;
flex-direction: row;
height: inherit;
}
.left {
width: 60%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
margin-top: 4.5rem;
margin-right: auto;
}
.left-con {
max-width: 40rem;
}
.right {
width: 40%;
display: flex;
justify-content: flex-end;
}
.image {
width: 100%;
}
.mid {
margin-top: 8rem;
margin-bottom: 1rem;
overflow: hidden;
width: 100%;
}
.opening {
font-size: 4.5rem;
letter-spacing: 2rem;
font-weight: 600;
display: inline-block;
}
.we {
color: #bc9496;
font-weight: 300;
}
.lower {
font-size: 1.2rem;
color: #bc9496;
}
.form {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 2rem;
width: 94%;
height: 3.5rem;
border-radius: 50px;
border: 1px solid #eadddf;
padding-left: 1rem;
overflow-x: hidden;
position: relative;
z-index: 0;
}
.email {
margin: 0;
padding: 0;
border: none;
width: 100%;
border: none;
}
.email::placeholder {
color: #eadddf;
}
.button {
display: flex;
justify-content: center;
align-items: center;
padding-right: 1rem;
padding-left: 1rem;
height: 100%;
width: 5.5rem;
border: none;
background: linear-gradient(to left, #f49694 0%, #f8acae 50%, #f7b6b8 100%);
border-radius: inherit;
color: white;
}
.width {
width: 6.75rem;
}
.warning {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 6px;
position: relative;
padding-right: 1rem;
}
.problem {
position: relative;
background-color: #e47579;
top: 1px;
padding: 0.5rem;
display: inline-block;
width: 134px;
z-index: 3;
}
.flex-con {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
height: 100%;
overflow: hidden;
position: relative;
z-index: 0;
}
.error {
width: 24px;
height: 24px;
flex-grow: 0;
}
.open {
position: relative;
left: 2rem;
}
.hidden {
display: none;
}
.problem::before {
content: "";
position: relative;
top: -39px;
left: 51px;
border-width: 15px;
border-style: solid;
border-color: transparent transparent #e47579 transparent;
}
@media screen and (max-width: 900px) {
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays site properly based on user's device -->
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100..700;1,100..700&display=swap"
rel="stylesheet">
<title>Frontend Mentor | Base Apparel coming soon page</title>
</head>
<body>
<div>
<img src="images/icon-error.svg" alt="">
</div>
<div class="container">
<div class="left">
<div class="left-con">
<img src="images/logo.svg" alt="">
</h3>
<div class="mid">
<h1 class="opening">
<span class="we">WE'RE</span> COMİNG SOON
</h1>
</div>
<div class="lower">Hello fellow shoppers! We're currenlty building our new
fashion store.Add your email below to
stay up-to-date with announcements and our launch deals</div>
<div class="form-con">sfddf
<form class="form" action="">
<label for="email" style="width: 80%; border: none;">
<input type="email" class="email" name="email" placeholder="Email Address">
</label>
<div class="flex-con">
<div class="warning">
<img class="error" src="images/icon-error.svg" alt="">
<!--
-->
</div>
<button class="button">
<img style="width: 1.2rem;" src="images/icon-arrow.svg" alt="Button Image">
</button>
</div>
</form>
</div>
<div class="problem">The `input` field is empty asdasdasd asdasdas
</div>
</div>
</div>
<div class="right">
<img class="image" src="images/hero-desktop.jpg" alt="">
</div>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>
How to hide server component on client component event in NextJS?
I have a simple setup:
Landing Page (server component)
- Form (client component)
- Footer (server component)
When a user submits the Form – I want to hide the Footer.
I’m pretty frustrated about how difficult NextJS makes this easy task.
Here’s what I’ve tried:
useState()in Landing Page – that doesn’t work, because I can’tuseStatein server componentzustandstore in Landing Page – doesn’t work, because I can’tuseRefin server componentrouter.queryin Landing Page – doesn’t work, because I can’t usenext/routerin server components, andnext/navigationdoesn’t havequery, so I need to useuseSearchParamsinstead, which is not available in server components… That was suggested by GPT4.
Now GPT4 suggests adding a CSS class and doing some document.getElementById stuff. At this point we’re basically back to 2006, using jQuery.
I ended up doing this disgusting thing in my form:
useEffect(() => {
if (isLoadingComparisonResults) {
const compareList = document.getElementById("compare-list");
if (compareList) {
compareList.style.display = "none"; // fml
}
}
}, [isLoadingComparisonResults]);
What am I missing?
You can see the app here: https://www.suburbcompare.com.au/ The part I’m trying to hide is the “Compare two suburbs”, after the user clicks “Compare” button in the form.
Could it be that I need to add some more proper URL routing? Like when a user submits the form it should take them to another page? I guess that could help, am I on the right track? Thank you!
(repost from https://github.com/vercel/next.js/discussions/64431)
Busboy NOT Working with Firebase/Firestorage
For the past 6 weeks I have tried probably every way to upload an image to firebase using Firebase-Admin, Nodejs, Busboy and Multer but no to avail.
I even tried to get the help of ChatGPT extension Grimoire and even that couldn’t solve the problem!
Always getting the same exact error:
Error uploading: Error: Unexpected end of form
> at Multipart._final (/Users/user/Desktop/project-Functions/functions/node_modules/busboy/lib/types/multipart.js:588:17)
> at prefinish (node:internal/streams/writable:906:14)
> at finishMaybe (node:internal/streams/writable:920:5)
> at Writable.end (node:internal/streams/writable:835:5)
> at onend (node:internal/streams/readable:946:10)
> at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
> storageErrors: []
My code relatively looks like this, although there were many other ways that I tried but they all look pretty much the same:
app.post("/uploadProfilePicture", upload.single("profileImage"), (req, res) => {
const file = req.file;
const { originalname, buffer } = file;
const blob = bucket.file("profile_pictures/" + originalname);
const blobStream = blob.createWriteStream({
metadata: {
contentType: file.mimetype,
},
});
blobStream.on("error", (err) => {
console.error(err);
res
.status(500)
.send({ message: "Failed to upload image.", error: err.toString() });
});
blobStream.on("finish", () => {
const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`;
res
.status(200)
.send({ message: "Image uploaded successfully", url: publicUrl });
});
blobStream.end(buffer);
});
“Why does my Axios request return a 404 Not Found error when including the ‘populate=*’ query parameter?”
**Home.jsx**
import { FetchDataFromApi } from "../../utils/api";
import { useEffect } from "react";
const Home = () => {
useEffect(()=>{
getCategory();
})
const getCategory = ()=>{
FetchDataFromApi("/api/categories/populate=*").then((res)=>{
console.log(res);
})
}
return (...)}
export default Home
------------------------------------------------------------------
**api.js**
import axios from "axios";
const params = {
headers:{
Authorization: "bearer " + "myApiToken"
}
}
export const FetchDataFromApi = async(url)=>{
try{
const {data} = await axios.get("http://localhost:1337" + url, params)
return data;
}catch (err){
console.log(err);
return err;
}
}
I’m trying to make a GET request to an API endpoint using Axios in my React application. When I include the query parameter ‘populate=*’ in the URL, I consistently receive a 404 Not Found error. However, when I remove this parameter, the request works fine, but then I am not able to get the details of image. someone’s code that I am following works though.
error-” Failed to load resource: the server responded with a status of 404 (Not Found) :1337/api/categories/populate=* “