I stumbled onto this interesting fact while I needed to find if the current frame/window is the top most or not. I realised that window.top !== window will do the trick. However after playing with it for couple of more minutes it became apparent that window.top.parent also has a property parent which refers to the window.top. So even window.top.parent.parent.top.parent === window.top. Does someone know the reasoning behind it apart from some crazy consistent interface?
Category: javascript
Category Added in a WPeMatico Campaign
javascript: How to update page widgets from a script before dispatching a change event to in input?
There is an input file widget on a web page.
When a button is clicked, the input widget is set to a filename on my pc.
The change does not immediately appear on the screen.
In the on Click event of the button, the last line dispatches a ‘change’ event to the input file widget.
The ‘change’ event works on input .Files[0], but the input widget still has not been updated with the file, so it fails when calling read As Text.
Then the file input widget is updated.
How can the file input box be updated before calling the ‘change’ event?
Here is the latest of what I have tried, my best version.
I was expecting to be able to read the file.
I picked up the ‘data Transfer of files’ from the web; this is used in the show Event button below.
<!DOCTYPE html>
<html>
<body>
<h1>Read a text file without manual choice of file</h1>
<input type="file" id="file" />
<br>
<div><h2>Output</h2></div>
<div id='output'>[waiting for text]</div>
<button type="button" onClick=showEvent("file:///c/HTMLLearning/coal.txt")>Coal</button>
<script>
const myFileContent = ['File Content'];
var myFileName = "";
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', function(event) {
input = document.getElementById('file');
var reader = new FileReader();
reader.onload = function () {
var node = document.getElementById('output');
node.textContent = reader.result;};
reader.readAsText(input.files[0]);});
function showEvent(filename) {
var myFilename = filename;
const myFile = new File(myFileContent, myFilename);
// Create a data transfer object. Similar to what you get from a drop event as event.dataTransfer
const dataTransfer = new DataTransfer();
// Add your file to the file list of the object
dataTransfer.items.add(myFile);
// Save the file list to a new variable
const fileList = dataTransfer.files;
// Set your input `files` to the file list
fileInput.files = fileList;
fileInput.dispatchEvent(new Event('change', { bubbles: true }));};
</script>
</body>
</html>
Why are regular expressions with capture groups treated differently in PHP and JavaScript? [duplicate]
I have just translated a working PHP function to Javascript. The purpose of the function is to transform the following text:
- [[chapter_1|Chapter One]]
- [[chapter_2|Chapter Two]]
Into:
- <a href=’javascript:displayText(“chapter_1”)’>Chapter One</a>
- <a href=’javascript:displayText(“chapter_2”)’>Chapter Two</a>
Obviously, my real text contains more chapters than two. The following PHP function works perfectly:
function href_convert($text) {
return preg_replace(
"/[[(.*)|(.*)]]/",
"<a href='javascript:displayText("$1")'>$2</a>";
$text);
}
But in JavaScript, i cannot get it working. Only the last capture group is replaced, and the others disappear …
function href_convert(text) {
let pattern = /[[(.*)|(.*)]]/g
let replacement = "<a href='javascript:displayText("$1")'>$2</a>";
return text.replace(pattern,replacement);
}
console.log(href_convert("[[chapter_1|Chapter One]]"));
console.log(href_convert("[[chapter_2|Chapter Two]]"));
I also tried it with a callback function, but the result is the same:
function href_convert(text) {
let pattern = /[[(.*)|(.*)]]/g
let replacement = (match, p1, p2) => {
return `<a href='javascript:displayText("${p1}")'>${p2}</a>`;
};
return text.replace(pattern,replacement);
}
console.log(href_convert("[[chapter_1|Chapter One]]"));
console.log(href_convert("[[chapter_2|Chapter Two]]"));
I would appreciate it if someone can tell me what is the problem.
How to add watermark to every pages in react-pdf
const Template1 = ({ data }) => {
const styles = StyleSheet.create({
page: {
position: "relative",
},
watermarkContainer: {
position: "absolute",
bottom: 30,
right: 30,
zIndex: 0,
opacity: 0.5,
},
watermark: {
width: 120,
},
});
return (
<Document>
<Page size="A4" style={styles.page}>
<Text>{data}</Text>
<View style={styles.watermarkContainer}>
<Image src={Watermark} />
</View>
</Page>
</Document>
);
};
If the content in the page tag fills multiple pages, the watermark only shows on the last page. How can I add a watermark on every page?
Build html table from output of Iframe contents [closed]
I’m trying build a widget for one of the ITSM applications using html.
This is the definition. But it is displaying contents in JSON format (that’s the return type, of course from the end_point)
I would like to build an html table (for better visualization) from the output.
Any help would be highly appreciated.
Thank you..


Higher oder components and how they work?
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import Loader from "../views/Loader/Loader";
import { FaInstagram } from "react-icons/fa";
const WithAuth = (WrappedComponent) => {
return function ProtectedComponent(props) {
// Accept props here
const [isAuthorized, setIsAuthorized] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem("token");
console.log("Token being sent:", token);
if (!token || token.trim() === "") {
setIsAuthorized(false);
return;
}
axios
.get("http://localhost:3000/users/authenticate", {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
console.log("Authentication Response:", response.data);
setIsAuthorized(response.data.message === "Authenticated");
})
.catch((error) => {
console.error("Authentication Error:", error.response?.data || error);
setIsAuthorized(false);
});
}, []);
if (isAuthorized === null) {
return <Loader />;
}
if (!isAuthorized) {
return (
<div className="unauthorized w-full h-screen flex flex-col justify-center items-center gap-5">
<h1 className="text-2xl">Unauthorized! Please log in.</h1>
<button
onClick={()=>{navigate('/login')}}
className="flex items-center justify-center gap-2 px-6 py-3 text-white font-semibold rounded-full bg-gradient-to-r from-pink-500 via-red-500 to-yellow-500 shadow-md hover:opacity-90 transition duration-300">
<FaInstagram className="text-xl" />
Sign in with Instagram
</button>
</div>
);
}
// Pass down all props to WrappedComponent
return <WrappedComponent {...props} />;
};
};
export default WithAuth;
AppRoutes :
import React from "react";
import { Routes, Route } from "react-router-dom";
import Register from "../views/register/Register";
import Login from "../views/login/Login";
import Profile from "../views/profile/Profile";
import WithAuth from "../components/withAuth";
const ProfileWithAuth = WithAuth(Profile); // Define it outside the component
const AppRoutes = () => {
return (
<Routes>
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
<Route path="/profile" element={<ProfileWithAuth />} />{" "}
{/* This now correctly passes props */}
</Routes>
);
};
export default AppRoutes;
my question is
- why pass props in ProtectedComponenet ? use corelation with vanilla js some exmaple ..
2 . return <WrappedComponent {…props} />; why we return {…props} in that wrapped funtion too ?
3.is there any resource to understand HOC
i tried to understand for gpt did some basic js porps accessing concept but acnt corelate can any one explain easily this Higher order components?
What is the use case of header file installed with wabt?
I don’t find any info about when to use the <wasm-rt.h> header and how, in the GitHub readme of wabt (WebAssembly binary toolkit).
I was originally thinking and trying out ways to compile a C file containing pthreads utilities used, into a wasm file which I can import in a JavaScript file.
I don’t know if wabt will be useful, so I installed wasmtime, wabt and wasi-sdk all of these. And now I am confused what to use. I seem to have wasmtime CLI installed but not the C APIs. The <wasmtime.h>, <wasm.h> and <wasi.h> headers are not found.
So, I have actually two questions, –
- When and how to use <wasm-rt.h> and wabt?
- Is it possible to compile my C code into WASM and use that WASM in js files in browsers and node?
I am here showing portions of my code so that you have an idea if this is viable or not.
My header file using pthreads –
/**
* SQL_MAP is an experimental custom data structure implemented by me.
* (currently for using in my personal projects)
* The name SQL_MAP comes from the inspiration from the power of foreign keys in a table can access primary key of some other table (power of RDBMS).
* Initially tried to do something similar.
*/
#ifndef SQL_MAP_H
#define SQL_MAP_H
#include <stddef.h>
#if defined(__GNUC__)
#define USE_THREAD_SAFETY
#include <pthread.h>
#else
#warning "Thread safety is disabled. Compile with gcc and pthreads to enable thread safety."
#endif
// -------------------------
// Structures and Typedefs
// -------------------------
typedef struct IndexNode {
char *key; // Interned key string
int *dataIndex; // Pointer to index in dataNodes array
struct IndexNode *next; // For chaining within buckets
} IndexNode;
typedef struct DataNode {
void *data;
} DataNode;
typedef struct SQLMap {
IndexNode **buckets; // Array of bucket pointers (chaining)
size_t bucketCount; // Number of buckets (capacity)
size_t entryCount; // Number of key-value entries
DataNode *dataNodes; // Dynamic array of data nodes
size_t dataCapacity; // Capacity of dataNodes
size_t dataCount; // Number of stored data nodes
#ifdef USE_THREAD_SAFETY
pthread_mutex_t mutex; // Mutex for thread safety
#endif
} SQLMap;
// -------------------------
// Function Prototypes
// -------------------------
// Create and initialize a new SQLMap instance.
SQLMap* sql_map_create(void);
// Insert or update a key-value pair in the SQLMap.
void sql_map_put(SQLMap *map, const char *key, void *value);
// Retrieve the value associated with the given key. Returns NULL if not found.
void* sql_map_get(SQLMap *map, const char *key);
// Remove a key-value pair from the SQLMap. Returns 1 if removed, 0 if not found.
int sql_map_remove(SQLMap *map, const char *key);
// Free all memory associated with the SQLMap.
// Note: The stored data (void*) is not freed; freeing it is the caller's responsibility.
void sql_map_free(SQLMap *map);
#endif // SQL_MAP_H
Portions of my C code using pthreads –
void sql_map_free(SQLMap *map) {
lock_map(map);
// Free each chain in the buckets.
for (size_t i = 0; i < map->bucketCount; i++) {
IndexNode *node = map->buckets[i];
while (node) {
IndexNode *temp = node;
node = node->next;
free(temp->dataIndex);
free(temp);
}
}
free(map->buckets);
free(map->dataNodes);
#ifdef USE_THREAD_SAFETY
pthread_mutex_destroy(&map->mutex);
#endif
unlock_map(map);
free(map);
// Optionally free the intern pool at program end.
free_intern_pool();
}
Best frontend technology [closed]
What front-end technology is best for making graphs, bars, charts etc. and the data for the same will come via APIs. The data will come from iOT in the form of REST APIs.
The data will be huge in the number of fields and rows. SEO is not required.
NA
Pdf Merging Library with size less then 7 mb
I am currently working on a project which is using Serverless lambda functions. The problem I am having is merging two pdf one uploaded by the user and second one generated by the code.
The library for pdf generation is puppeteer which doesnt support pdf merging.
Is there any library or way to merge these pdfs???
i have tried merge-pdf-buffers but it have dependency of more than 50 mb, too large, then tried coherentpdf which had no dependencies with a size of 8.4mb in node_modules. they are working but size is causing deployment issues for me. I need a library which is less then 7 mb in size or a workaroud.
Keep values on hold and compare new values with those on hold
Using one Observable in RxJS, all incoming values should be treated like such:
-
Keep each value on hold for N seconds.
-
If within those N seconds, another value matching a custom matcher comes in, then ignore the new value. I.e. compare each new value with all values currently on hold. Values already pushed to the subscribers do not matter. I need a customer matcher function, plain
distinctwon’t do (dealing with objects here and e.g.{ids:['a','b']}should equal{ids: ['b','a']} -
If within those N seconds, another value matching some custom criteria comes in, then merge the new value and the original value to one value, using a custom function. Again: Only care about values on hold, do not care about previous values already pushed to subscribers.
-
For both cases: It should not matter if in between different values come in. I.e. I cannot use operators which simply compare previous values (like
distinctUntilChanged) -
After N seconds have passed, push to subscribers.
How do I do that? (Tried to fiddle with scan, mergeScan, windowTime and some other operators but could not figure it out.)
Edit: As per comment request here’s the current code-snippet, but it won’t help much I guess:
const { from } = require('rxjs');
const { windowTime, concatMap, distinct, tap, filter, map, debounceTime, distinctUntilChanged, scan, mergeScan } = require('rxjs/operators');
const myInpExamples = [
{userId: "userA", ids: ["aa"]},
{userId: "userB", ids: ["cc"]},
{userId: "userA", ids: ["aa"]},
{userId: "userA", ids: ["aa"]},
{userId: "userB", ids: ["bb"]},
{otherIds: ['11']},
{otherIds: ['22']}
]
const arrayDataObservable$ = from(myInpExamples);
const dataPipeline = arrayDataObservable$.pipe(
windowTime(1000),
concatMap((obs) => obs.pipe(distinctUntilChanged(
(prev, curr) => {
return JSON.stringify(prev) === JSON.stringify(curr)
}
)))
)
const subscribeToDataPipeline = subscriberName => {
return dataPipeline.subscribe(val => {
console.log(subscriberName + ' received: ' + JSON.stringify(val, null, 2));
})
}
const handleSubscriptionToDataPipeline = () => {
const subscription1 = subscribeToDataPipeline('Subscriber1');
}
handleSubscriptionToDataPipeline();
Expected outcome here is that Subscriber1 gets those values:
- {userId: “userA”, ids: [“aa”]}
- {userId: “userB”, ids: [“cc”]}
- {userId: “userB”, ids: [“bb”]}
- {otherIds: [’11’]}
- {otherIds: [’22’]}
Angular element is being null when using query selector
I have a checkbox whereby on clicking on it, it should cause inputs and dropdowns to be disabled. I did the change on my local machine and everything is working fine. However, on my environment, im getting the element null causing it not to be disabled.
private disableControls() {
const isPizza = this.dynamicFormMenuForm.get('menuHasPizza');
const pizzaOptions = this.dynamicFormMenuForm.get('menuPizzaOptions');
const pastaOptions = this.dynamicFormMenuForm.get('menuPastaOptions');
const saladChoice = this.dynamicFormMenuForm.get('menuSaladChoice');
const dessertChoice = this.dynamicFormMenuForm.get('menuDessertChoice');
if (isPizza?.value == false) {
saladChoice?.enable();
pastaOptions?.enable();
pizzaOptions?.disable();
if (saladChoice?.value == false) {
dessertChoice?.disable();
}
}
else {
saladChoice?.reset(false);
saladChoice?.disable();
dessertChoice?.disable();
}
if(isPizza){
isPizza.valueChanges.subscribe
((newValue) => {
if (newValue === true) { // Pizza
selected
pizzaOptions?.enable();
saladChoice?.patchValue(false);
saladChoice?.disable();
const dessertElement = document.querySelector(`[ng-reflect-name="menuDessertChoice"]`) as HTMLSelectElement;
dessertChoice?.patchValue(null);
dessertElement.selectedIndex = 0;
dessertElement.disabled = true;
const pastaElement = document.querySelector(`[ng-reflect-name="menuPastaOptions"]`) as HTMLSelectElement;
pastaOptions?.patchValue(null);
pastaElement.selectedIndex = 0;
pastaElement.disabled = true;
}
});
}
}.. in the query selector, the elements are being null and hence not disabled on environment. Im calling the function on ngafterviewinit
How to get all elements containing a specified string, regardless of element type
How can I get all elements containing a specific string, regardless of element type, e.g. <div>, <p>, <span>, <td>, etc.? I cannot use any class, id, or other attributes. For example, how can I highlight in yellow the elements containing the word “YELLOW” in the following HTML code:
<div>
red
</div>
<p>
blue, <span>*** YELLOW ***<span>, orange
</p>
<div>
*** YELLOW ***
</div>
<p>
cyan
</p>
<p>
*** YELLOW ***
</p>
<table>
<tbody>
<tr>
<td>purple</td>
<td>*** YELLOW ***</td>
<td>
<p>
lime, pink <span>*** YELLOW ***<span>, magenta
</p>
</td>
<td>silver</td>
</tr>
</tbody>
</table>
runtime error in leet code in javascript but complier works fine
var lengthOfLongestSubstring = function (s) {
let uniqueSubString = ""
for (let i = 0; i < s.length; i++) {
let substring = s[i]
for (let j = i + 1; j < s.length; j++) {
if (substring.includes(s[j])) {
break
} else {
substring += s[j]
}
}
if (uniqueSubString.length < substring.length) {
uniqueSubString = substring
}
}
return uniqueSubString.length
};
Runtime Error
undefined:1
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
Line 44: Char 17 in deserializer.js (deserializer.toString)
Line 32: Char 36 in solution.js (Object.<anonymous>)
Line 16: Char 8 in runner.js (Object.runner)
Line 24: Char 26 in solution.js (Object.<anonymous>)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
Node.js v20.10.0
get this error when running in leetcode. in other compilers it work accurately.
it works and provide right output for all compiler but when try to run in leetcode it gets the error
How to Use Dropdown Arrow to Show AG Grid Rich Select Cell Editor List
I’m evaluating AG Grid to use as a data grid versus using Handsontable. One hang-up is their “select cell editor” feature. I’d like to change its behavior to behave like the Handsontable dropdown as follows:
- Single-click the cell to select it ONLY, without the dropdown list showing.
- Double-click the cell to show the dropdown list.
- Single-click on a down arrow icon, located on the far right-hand side of the cell to show the dropdown list.
In sum, I want to show the dropdown list only when the user either 1) double-clicks on the cell or 2) single-clicks on the drown arrow icon. Again, behave like Handsontable does.
It’s default behavior is to require double-click on the cell to show the dropdown list which I don’t want. As an alternative, you can also change the “singleClickEdit” property to “true” to only require a single click to show the dropdown list, but I don’t want that either because it doesn’t allow you to just select the cell without the dropdown list showing.
To get my desired behavior I’ve left the default behavior of requiring double-click to show the dropdown list. Then, I used cell rendering to add a dropdown arrow icon (using Bootstrap) and tried adding script to that icon to show the dropdown list when clicked. However, I’m having two problems.
- I cannot position the icon to the right side of the cell
- I cannot figure out the script needed to show the dropdown list when the icon is clicked.
Any ideas? Or, is there a configuration setting I can use where I would not have to use cell rendering? Or is cell rendering the only option?
Example and Links provided below:
Example:
let gridApi;
class ClassDropdown {
init(params) {
this.eGui = document.createElement("div");
this.eGui.innerHTML = `<span class="span-age">${params.value}</span><i class="bi bi-chevron-down"></i>`;
this.iconChevron = this.eGui.querySelector(".bi-chevron-down");
this.iconChevron.onclick = () => alert("this should show the dropdown list");
}
getGui() {
return this.eGui;
}
refresh() {
return false;
}
destroy() { }
};
const languages = ["English", "Spanish", "French", "Portuguese"];
const gridOptions = {
defaultColDef: { width: 200, editable: true, },
columnDefs: [
{ field: "language", cellEditor: "agRichSelectCellEditor", cellEditorParams: { values: languages, }, singleClickEdit: true },
{ field: "test", cellEditor: "agRichSelectCellEditor", cellEditorParams: { values: languages, }, cellRenderer: ClassDropdown, cellClass: 'my-class' },
],
rowData: [
{ language: "English", test: "English" },
{ language: "Spanish", test: "English" },
{ language: "French", test: "English" },
{ language: "English", test: "English" }
],
};
document.addEventListener("DOMContentLoaded", () => {
const gridDiv = document.querySelector("#myGrid");
gridApi = agGrid.createGrid(gridDiv, gridOptions);
});
Links:
AG Grid cell dropdown example:
https://www.ag-grid.com/javascript-data-grid/provided-cell-editors-rich-select/
Handsontable cell dropdown example:
https://handsontable.com/docs/javascript-data-grid/dropdown-cell-type/
How to trim the formatted HTML contents of a contenteditable element?
I have the following simple contenteditable table cell:
When I press the Test button, it outputs the innerHTML and innerText values inside the box.
innerHTML: (note the 4 <br> tags at the end)
<i style="font-size: 14.6667px;">This</i><span style="font-size: 14.6667px;"> is one line</span><br style="font-size: 14.6667px;"><br style="font-size: 14.6667px;"><span style="font-size: 14.6667px;">This is </span><u style="font-size: 14.6667px; font-weight: bold;">another</u><span style="font-size: 14.6667px;"> </span><span style="font-size: 14.6667px;">line</span><br style="font-size: 14.6667px;"><br><br><br style="font-size: 14.6667px;">
innerText:
This is one line
This is another line
What I want to achieve: be able to “trim” the innerHTML value (i.e., remove blank lines) while keeping the formatting. This is simple to do with the innerText value (just something like document.getElementById("id").innerText.trim()), but the formatting is gone. I can’t see any reference to “trim” an innerHTML value. Is there a way to do this using either Javascript or JQuery?
function test() {
var html = document.getElementById("inputBox").innerHTML;
var text = document.getElementById("inputBox").innerText;
console.log(`html:n${html}`);
console.log(`text:n${text}`);
}
table {
width: 100%;
}
td#inputBox {
height: 100px;
border: 1px solid #020202;
}
<table>
<tr>
<td contenteditable="true" id="inputBox"></td>
</tr>
</table>
<button onclick="test()">Test</button>
