When using the t.clik function of testcafe, clicking on a specific element will click on its child elements, resulting in unsatisfactory operation. How can I force click on the element itself without responding to clicks on child elements?
Category: javascript
Category Added in a WPeMatico Campaign
How to make Jest depend on other test?
In PHPUnit, there is Test dependencies feature but in Jest I don’t see any like that.
I have tests just like this. (The whole Node.js project is in "type": "module"
.)
import fs from 'node:fs';
describe('Description of test file 1', () => {
test('Test on file1', () => {
expect(true).toBeTruthy();
// create file for use in file2. also use it for test here too.
});
});
Above is file1.test.mjs.
import fs from 'node:fs';
describe('Description of test file 2', () => {
test('Test on file2', () => {
expect(false).toBeFalsy();
// use a file that created in file1. test it then delete.
});
});
Above is file2.test.mjs.
I want to make sure that file2.test.mjs runs after file1.test.mjs.
How to mark it to run after file 1 (or also know in PHPUnit as depends on file1)?
How to hide only the progress bar in YouTube IFrame (controls:1) and still allow quality selection?
I’m embedding a YouTube video using the IFrame Player API.
I want to hide only the progress bar (seek bar) but still allow users to change video quality via the gear icon.
I tried using controls: 0
, but it hides the entire YouTube UI, including the quality selector.
Setting controls: 1
shows everything, but I only want to keep the quality menu and remove the timeline/progress bar.
Also, using CSS like this doesn’t work:
iframe .ytp-progress-bar {
display: none !important;
}
Because the iframe is cross-origin, I can’t access or style the internal elements of the player.
Is there any way to hide just the progress bar while keeping the quality selector visible?
Even a hacky workaround would be appreciated.
What I’ve tried:
playerVars.controls = 0
→ hides everything, including quality menu
playerVars.controls = 1
+ CSS mask → can’t style inside iframe
setPlaybackQuality('hd1080')
→ deprecated / doesn’t work
My goal:
Hide only the timeline/progress bar
Keep the quality menu available (or programmatically set video quality)
Any ideas, tricks, or workarounds?
Thanks in advance!
DOM vs Canvas performance for bullet comments (danmaku). Do I really need WebGL?
I’m building a danmaku (bullet comments) system in a project that consists of HTML + CSS + TypeScript.
So far, I’ve tried two approaches:
Direct DOM manipulation
I create <div>
or <img>
elements for each danmaku.
Position updates are done using CSS transform: translate3d(...)
for smooth GPU acceleration.
Performance is actually quite good, but I still see some unavoidable jitter/shaking when many elements are moving, especially with <img>
tags.
Canvas 2D API
I render all danmaku on a <canvas>
.
Surprisingly, this feels slower than DOM: more stuttering and even screen tearing/flickering.
Even with an offscreen buffer (OffscreenCanvas
or double buffering), it doesn’t feel as smooth as DOM.
I also considered a third approach:
Pre-render each danmaku’s text into a small <canvas>
once.
Later, just drawImage those cached canvases every frame instead of calling fillText.
But I’m worried this might introduce too much complexity and memory overhead if there are many comments.
Now I’m wondering:
Is this just the limitation of Canvas 2D API, and the only way to get smooth danmaku rendering at scale is WebGL?
Or are there known techniques to make Canvas-based text/images perform as well as DOM (e.g., caching, texture atlas, bitmap reuse)?
In practice, what do large-scale video platforms (like Bilibili, Niconico) use for this?
Any advice or references would be appreciated!
Following JavaScript code works on desktop version of Firefox, Safari and Chrome but does not on the iPhone version of Firefox, Safari
Following JavaScript code works on desktop version of Firefox, Safari and Chrome but does not on the iPhone version of Firefox, Safari.
const jsDate = new Date();
const year = jsDate.getFullYear();
const month = jsDate.getMonth() + 1;
const day = jsDate.getDate();
const start = new Date(`${year}-${month}-${day}`);
console.log('start', start);
How to hide/handle google one tap when inside a mobile in app browser?
Similar to this , google one tap sign in for my site, when inside a 3rd party mobile app’s in app browser (e.g. instagram, youtube, etc) will silently fail with a white screen.
This not being supported is an intentional behavior
- https://support.google.com/faqs/answer/12284343?hl=en-GB
- https://developers.googleblog.com/en/modernizing-oauth-interactions-in-native-apps-for-better-usability-and-security/
- https://developers.googleblog.com/en/upcoming-security-changes-to-googles-oauth-20-authorization-endpoint-in-embedded-webviews/
What is the best way to handle this situation for a better user experience? As per google’s recommendation the 3rd party mobile apps should defer to using the system browser instead. But that isn’t in our control as our site could be opened/navigated to by the in-app browser.
Non-viable solutions I’ve searched:
- Hiding google one tap based on user agent isn’t viable, as there’s no standardized user agent property to check if it’s an in app browser (see an attempt at https://github.com/f2etw/detect-inapp/blob/master/src/inapp.js)
- Check viewport if the browser is mobile,but this doesn’t discriminate if it’s a system browser (which would work fine) or in app browser (which fails)
Why is it when I manually line break my code is fine but on auto line break my connecting logic breaks?
Basically I have a neon customisation website where customers can text in any text they want and see it on a live preview canvas, one of my backboard options – cut to shape, adds an ‘acrylic’ backboard behind my neon. The problem is there’s a connector that connects inbetween lines to make the backboard like one unified body, now the issue is when I align text center or right (default is left) when the text soft line wraps (automatically due to width restraint), the connector is confused when I tap align right or center to the whole text and protrudes out on the left hand side making a sharp shape that sticks out where it should curve downwards. On manual (enter) line breaks, the logic works perfectly and the connector is smooth on either side whether it’s left, center or right, why is that?
I tried everything by changing the math of the connector but I don’t think the curve is the issue, I think the issue is that it can’t discern between auto vs manual and has different logic for each (a given because it gets the bounding client to measure actual text width after a soft line wrap)
How do I make a draggable image when on zoom: it stops at edge of the window (JS, jQuery)
I am making an Image Viewer for my website for when on zoom and when on drag, it will stops at the edge of the window (will not pull more further) and all I tried wasn’t working as expected. This is the current I have
HTML
<div id="imageModal">
<div id="blackout"></div>
<span class="close"></span>
<div id="modalImage">
<div id="containerLimit">
<img src="">
</div>
</div>
</div>
CSS
/* Modal blackout background */
#imageModal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
transition: opacity 0.2s ease, visibility 0.2s ease;
z-index: 240009;
}
#blackout {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000000c0;
opacity: 0;
transition: opacity 0.2s ease;
}
.imgauto:hover, .imgautofull:hover {
cursor: pointer;
}
/* When the modal is active */
#imageModal.show #blackout {
opacity: 1;
}
#imageModal.show {
opacity: 1;
visibility: visible;
}
/* Modal content (image box) */
.modal-content {
position: relative;
border-radius: 10px;
max-width: 90%;
max-height: 90%;
display: flex;
justify-content: center;
align-items: center;
}
/* The full-size image */
#modalImage {
position: fixed;
z-index: 240010;
transform: scale(0.9);
transition: 0.2s ease;
margin: 50px;
display: flex;
align-items: center;
justify-content: center;
}
#modalImage img {
position: relative;
max-width: 80%;
max-height: 80vh;
transition: 0.2s ease;
border-radius: 0px;
}
#imageModal.show #modalImage {
transform: scale(1);
}
/* Close button */
.close {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: white;
z-index: 1;
}
.img-zoom {
cursor: grab;
transform: scale(2);
/*width: auto;*/
/*height: auto;*/
/*max-width: none;*/
}
.img-zoom:active {
cursor: grabbing;
}
#modalImage, #containerLimit {
position: fixed;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
}
#containerLimit img {
pointer-events: auto;
}
JS
// imgauto
document.addEventListener("DOMContentLoaded", function () {
const modal = document.getElementById("imageModal");
const modalImg = document.getElementById("modalImage");
const inImg = modalImg.querySelector("img");
const closeBtn = document.querySelector(".close");
// Select all images with the class 'imageToView'
const imageContainers = document.querySelectorAll(".imgauto, .imgautofull");
imageContainers.forEach(container => {
const img = container.querySelector("img"); // Get the image inside each div
if (!img) return; // Skip if no image inside the div
container.addEventListener("click", function () {
modal.style.display = "flex";
setTimeout(() => modal.classList.add("show"), 10);
inImg.src = img.src;
document.body.classList.add("modal-open");
});
});
closeBtn.addEventListener("click", function () {
closeModal();
});
modal.addEventListener("click", function (e) {
if (e.target === modal) {
closeModal();
}
});
let isDragging = false;
let zoomed = false;
function closeModal() {
modal.classList.remove("show");
inImg.classList.remove('img-zoom');
disableDrag("#modalImage img");
isDragging = false;
zoomed = false;
setTimeout(() => {
modal.style.display = "none";
document.body.classList.remove("modal-open");
}, 300); // Match the transition duration
}
// drag on zoom
let sX, sY;
const dragFound = 5; // pixels before it's considered drag
function updateContainer() {
const ww = window.innerWidth;
const wh = window.innerHeight;
console.log("-----------------------------------------");
console.log(`WINDOW: width: ${ww} height: ${wh}`);
// inImg.addEventListener("transitionend", updateContainer, { once: true });
// const rect = inImg.getBoundingClientRect();
// const bw = rect.width;
// const bh = rect.height;
// console.log(`IMAGE: width: ${bw} height: ${bh}`);
modalImg.style.width = ww + 'px';
modalImg.style.height = wh + 'px';
console.log(`MASK: width: ${ww} height: ${wh}`);
const cont = document.getElementById("containerLimit");
cont.style.width = ww + "px";
cont.style.height = wh + "px";
}
imageContainers.forEach(container => {
const img = container.querySelector("img"); // Get the image inside each div
if (!img) return; // Skip if no image inside the div
container.addEventListener("click", function () {
updateContainer();
});
});
// function enableDrag() {
// $(inImg).draggable({
// // containment: "#containerLimit",
// // scroll: false,
// // drag: function(event, ui) {
// // if (ui.position.top > 0) {
// // ui.position.top = 0;
// // }
// // var maxtop = ui.helper.parent().height() - ui.helper.height();
// // if ( ui.position.top < maxtop) {
// // ui.position.top = maxtop;
// // }
// // if ( ui.position.left > 0) {
// // ui.position.left = 0;
// // }
// // var maxleft = ui.helper.parent().width() - ui.helper.width();
// // if ( ui.position.left < maxleft) {
// // ui.position.left = maxleft;
// // }
// // }
// containment: "window"
// });
// }
function enableDrag(selector, maskSelector) {
let $img = $(selector);
let $mask = $(maskSelector);
if ($img.length === 0 || $mask.length === 0) {
console.error("Error: One or both of the elements were not found.");
return;
}
console.log("FUNCTION: [jQuery draggable] USE");
$img.css({top:0, left:0});
// disableDrag(selector); // prevent duplicates
// Cache dimensions to improve performance during drag
let maskWidth = $mask.width();
let maskHeight = $mask.height();
// let imgPos = $img.offset();
let imgWidth = $img.width();
let imgHeight = $img.height();
// console.log("mw, mh: ", maskWidth, maskHeight);
// console.log("ip: ", imgPos);
// console.log("iw, ih: ", imgWidth, imgHeight);
// Calculate bounds
let minLeft = maskWidth - imgWidth;
let maxLeft = 0;
let minTop = maskHeight - imgHeight;
let maxTop = 0;
// let x1 = (imgPos.left + maskWidth) - imgWidth;
// let y1 = (imgPos.top + maskHeight) - imgHeight;
// let x2 = imgPos.left;
// let y2 = imgPos.top;
// console.log("x1, y1: ", x1, y1);
// console.log("x2, y2: ", x2, y2);
$img.draggable({
drag: function(event, ui) {
// Constrain the position
ui.position.left = Math.min(maxLeft, Math.max(minLeft, ui.position.left));
ui.position.top = Math.min(maxTop, Math.max(minTop, ui.position.top));
}
});
// $img.draggable({
// containment: [x1, y1, x2, y2]
// });
}
function disableDrag(selector = "#inImg") {
let $img = $(selector);
if ($img.draggable("instance")) {
console.log("FUNCTION: [jQuery draggable] DESTROY");
$img.draggable("destroy");
} else {
console.log("FUNCTION: [jQuery draggable] No draggable instance found for", selector);
}
}
// Mouse events
modalImg.addEventListener("mousedown", function (e) {
sX = e.clientX;
sY = e.clientY;
isDragging = false;
});
modalImg.addEventListener("mousemove", function (e) {
if (e.buttons === 1) {
const currentX = e.clientX;
const currentY = e.clientY;
const distance = Math.sqrt(
Math.pow(currentX - sX, 2) + Math.pow(currentY - sY, 2)
);
if (distance > dragFound) {
isDragging = true;
enableDrag("#modalImage img", "#containerLimit");
console.log("MOUSE EVENT: Dragging");
}
}
});
modalImg.addEventListener("mouseup", function () {
if (!isDragging) {
// Toggle zoom on click
zoomed = !zoomed;
if (zoomed) {
inImg.classList.add("img-zoom");
// Enable draggable when zoomed
enableDrag("#modalImage img", "#containerLimit");
} else {
inImg.classList.remove("img-zoom");
// Disable draggable when zoomed out
disableDrag("#modalImage img");
// Reset to original position
inImg.style.left = "0px";
inImg.style.top = "0px";
inImg.style.transform = ""; // optional: clear inline transforms
}
requestAnimationFrame(() => updateContainer());
} else {
// Drag release – keep zoomed in
if (!zoomed) {
zoomed = true;
inImg.classList.add("img-zoom");
enableDrag("#modalImage img", "#containerLimit");
requestAnimationFrame(() => updateContainer());
}
}
isDragging = false;
});
// Update container size when window resizes
window.addEventListener("resize", () => {
updateContainer();
});
});
NOTE: I have made a comment on some of the code in JS because I might re-use it in some cases.
The current code I have is that when on zoom and when on drag, it will enable draggable. But the result is the draggable element stays still as it is.
And from my custom code, I’ve made a JSFiddle one that works fine (pre-scaled) is that I get the width and height from the window and the image, then get the overflowing values, then set the container to width = window width + overflow width * 2, height = window height + overflow height * 2 which it does work. But the problem is the .draggable()
still uses the original size of the image resulting the image go past the containment
I’ve tried the stack overflow post (Asked on 2009) where they were creating an interface to allow a user to zoom in on an image and drag the zoomed version around within a clipping mask div.
But when I applied the code to my very code, it gave me a reverse drag. Is there any way to make this possible?
CSS Grid layout: items reorder unexpectedly — how to preserve DOM order?
I want to create a masonry style layout
Here is how i did it but it didn’t work as expected:
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
background-color: #2196F3;
padding: 10px;
grid-auto-flow: row;
}
.grid-container>div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 30px;
}
.item:nth-child(2n) {
grid-row-start: 0;
grid-row-end: span 2;
}
<div class="grid-container">
<div class="item item1">1</div>
<div class="item item2">2</div>
<div class="item item3">3</div>
<div class="item item4">4</div>
<div class="item item5">5</div>
<div class="item item6">6</div>
<div class="item item7">7</div>
<div class="item item8">8</div>
<div class="item item9">9</div>
<div class="item item10">10</div>
<div class="item item11">11</div>
<div class="item item12">12</div>
</div>
Here are my results:
Answers are appreciated to me, thanks for the help
How can I also include nested array in my XLSX?
I’m trying to export a data using XLSX with a specific user, the problem I’m currently facing, is I also want to include the list of publications.
result.json
{
"id": "aKbteocWBNME8OgWlRpXz0EtBE3i3M7g",
"email": "email.com",
"orcid": "123123",
"first_name": "John",
"middle_name": "Doe",
"last_name": "Smith",
"publications": [
{
"id": "0a2828e5-73f1-42a3-8a08-30d19562e346",
"title": "asdsa",
},
{
"id": "d152c617-f049-4042-b498-119e8d70bbca",
"title": "asdsd",
},
{
"id": "e042e830-53f0-45cb-b820-fb6887ee2e81",
"title": "2024",
}
],
"_count": {
"publications": 3
},
"_sum": {
"citations": 2
}
}
This is my export function in client side.
const exportFaculty = () => {
const rows = [{
id: exportData.id,
email: exportData.email,
name: `${exportData.first_name || ''} ${exportData.middle_name || ''} ${exportData.last_name || ''}`.trim(),
department: exportData.department,
college: exportData.college,
}];
const worksheet = XLSX.utils.json_to_sheet(rows);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Faculty");
XLSX.writeFile(workbook, `${exportData.first_name} ${exportData.middle_name} ${exportData.last_name}.xlsx`, { compression: true });
};
This the export data im trying to approach.
download a pdf through playwright can open the pdf page but not trigger the download
trying to download a sample pdf in playwright, the pdf web page is opened but not triggering the download event, ultimately causing the timeout event.
error:
page.waitForEvent: Timeout 30000ms exceeded while waiting for event "download" =========================== logs =========================== waiting for event "download"
Even tried to click the download button still doesn’t work either.
await pdfPage.click("[id='download']"); // might get stuck here with timeout
error:
page.click: Timeout 30000ms exceeded. Call log: [2m - waiting for locator('#download')[22m
Call log: [2m - waiting for locator('#download')[22m at
Here is the code example
const browser = await chromium.launch({
headless: false, // Set to true for headless mode
executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const context = await browser.newContext({
acceptDownloads: true
});
let pdfUrl = 'https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf';
await downloadFileAndCheck(context,pdfUrl);
const downloadFileAndCheck = async (
context: any,
pdfUrl:string,
) => {
console.log(`open `);
const pdfPage = await context.newPage();
await pdfPage.goto(pdfUrl);
console.log(`trying to click `); // working
await pdfPage.click("[id='download']"); // might get stuck here with timeout
console.log(`click... `); // not working
const downloadPromise = pdfPage.waitForEvent('download'); // might get stuck here with timeout
const download = await downloadPromise;
console.log(`download as `);
const savePath = path.resolve(__dirname, `test.pdf`);
await download.saveAs(savePath);
const downloadPath = await download.path();
};
so I tried to have playwright click the download ‘button’, but still get stuck
Unable to output successfully compiled react component into DOM
I’ve trying to integrate react into an existing project. I’m starting by setting up a simple button component to get started. The project is an express app that uses handlebarsjs to handle the views.
I have created the jsx file with correct syntax and successfully compiled to an output file. I am then importing that output file into my main.js script which is requested by the main layout view.
I can see the successful compilation by babel in the dist directory. I don’t have any errors in the browser console. however, for some reason the component is not rendered on the page.
What could I be overlooking?
main-layout.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- express will automatically assume an requested file with .css or .js
file extension is under /public, which can be excluded from href for that reason -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="/css/main.css">
<script src="js/bootstrap.min.js"></script>
<title>{{ pageTitle }}</title>
</head>
<body class="{{ firstname }}">
{{> header }}
<div class="container-xl">
{{{ body }}}
<div id="react-app"></div>
</div>
{{> footer }}
<script type="text/javascript" src="/js/lottie.js"></script>
<script type="text/javascript" src="/js/main.js"></script>
</body>
</html>
main.js
import submitHandler from './form.js';
import button from './components/button.js';
import lottieInit from './animations/lottie-handler.js';
import ReactButton from '../../dist/bca-react-component-library/button.js';
import { createRoot } from 'react-dom/client';
function loadButton() {
const root = createRoot(document.getElementById('react-app'));
root.render(
<ReactButton />
);
console.log('rendered ReactButton');
}
window.addEventListener("load", runAllFunctions);
function runAllFunctions() {
submitHandler();
lottieInit();
button();
loadButton();
}
button.js (compiled)
export default function ReactButton() {
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", null, "click here"));
}
button.js (pre-compile)
export default function ReactButton() {
return (
<>
<button>click here</button>
</>
);
}
babel.config.json
// .babelrc or babel.config.json
{
"presets": ["@babel/preset-react"]
}
Full Stack Programming Riddle
I’m currently working on a programming challenge and got stuck on the following step:
Step 1: The Cryptographic Riddle
Your first task is to decipher a riddle to obtain critical configuration information. You have access to two strings:
File 1 (Base64 message):
VGhlIGtleSB3aWxsIGJlIG9uZSBiZWZvcmUgaXRzIHRpbWUgYW5kIHdpbGwgc3RhbmQgZm9yIGFuZXRuaXR5IGFuZCBzZXJ2ZSBhcyBhIHNvdXJjZSBvZiBpbnRlZ3JhdGlvbi4gQ29udmVuYWRlcyB3aWxsIGJlIGJyb2tlbi4gT3VyIHJldHVybiBpcyB0aGUgZ2lmdCBvZiBjaGFvcy4=File 2 (Encrypted message):
f867490acb2f567b57e7f7b31b81609162e24536717a6a7c4f1c9c4c1a51a1969a53Instructions:
Decode File 1 to find the key needed to decrypt File 2. The result of the decryption will be the DATABASE_URL and SUPER_SECRET_TOKEN needed for the next step.
I was able to decode File 1 using a Buffer approach, and it returned the following phrase:
The key will be one before its time and will stand for anetnity and serve as a source of integration. Convenades will be broken. Our return is the gift of chaos.
Now, this is where I got stuck.
I suspect the words “anetnity” and “convenades” are intentionally misspelled and might be clues, but I haven’t figured out how to move forward. I tried using AI tools but ended up wasting time without real progress.
Does anyone have any insights or experience with solving cryptography puzzles like this?
jQuery addition in JavaScript is not working and giving wrong answers [closed]
I tried to add two numbers with the jQuery basic arithmetic plugin in Node.js, but it was giving me strange and erratic answers. Here’s my code:
require("make-jquery-global")()
require("jquery-basic-arithmetic-plugin")
process.stdout.write(jQuery.add(2, 2))
But it outputs 5. I tried several other additions, but it did not work. Please help me! I know you think I’m dumb and just can add normally, but my friend told me you need to use jQuery or addition is slow and takes forever. And he’s always right. This question is not a troll and joke so stackoverflow don’t get mad at me. Thanks for the help
Debugging details:
On Windows 10 on a MacBook Pro, running the latest version of Node.js. The exact code in this is needed to reproduce, and also NPM installing the packages mentioned: “make-jquery-global” and “jquery-basic-arithmetic-plugin”
Suddenly getting UNABLE_TO_VERIFY_LEAF_SIGNATURE
Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE
I have started suddenly getting the signature error. I have changed nothing in my code, and nothing in my network or VPS network. I am completely aware there are many forum posts on here with the same issue. I have gone through them and attempted some of the solutions, including ssl-root-cas
.
I also have not been able to find something relating to axios. I have tried the same request with fetch. I can complete the request with Postman.
Code:
const options = {
method: 'POST',
url: 'example.com',
headers: {
'content-type': 'application/json',
},
rejectUnauthorized: false,
data: {
grant_type: 'client_credentials',
email: '[email protected]',
password: 'sdfsdjkfhsdfks',
},
};
axios
.request(options)
.then(function (response) {
console.log(response.data.access_token);
APIKey = `Bearer ${response.data.access_token}`;
})
.catch(function (error) {
console.log(error);
});
This is a system-breaking error, so any help is appreciated.