I have to create UI interface for create category hierarchy up to 7 level. Like – shoes->boots->bata…
Also need functionality to edit created category hierarchy.
This I have to create in Markojs. Mainly I need help in UX design for help. Any reference or any code base please provide. I am new to this so getting stuck UX design. Facing challenge to visual the UI screen. Please help in any way. Advance tahnks
Category: javascript
Category Added in a WPeMatico Campaign
Cannot seem to get jquery scrollTop to work
Here is my situation. I have a website where users message one another back and forth. The user has a list of open conversations, clicks one, it opens a modal box that is populated with messages via jquery and an ajax call to a php script. All of this works fantastically.
Of course, some conversations get very long, so to save users from manually scrolling to the bottom every time, I’d like to use jquery to jump to the end. But for the life of me, I can’t get this to work.
I wondered if it was an asynch issue – maybe it was trying to scroll before the HTML of the div was populated from my remote script? I played with delays, but that didn’t help. So for testing, I added a “scroll” link and a function with the following simple code:
var d = $('#wrap_connect');
d.scrollTop(d.prop("scrollHeight"));
No joy, even though the user (me) obviously isn’t clicking the link until well after the content is populated. Now mind you, I tried many ways of doing this. Animate, non animated, one line, two lines, etc, etc. No matter what I do, it never scrolls down.
For debugging, I added an alert:
alert('height: '+d.prop("scrollHeight"));
It gives me the height of the container (#wrap_connect) – and changes accordingly if I shrink/expand the window. So jQuery agrees that there is scrollHeight there, it sees the target div, I get no errors in developer tools… but it just won’t jump to the bottom.
I have tried giving my #wrap_content box the CSS property of “overflow-y: scroll”. I’ve tried without.
I wonder if there is some other CSS conflict that I’m unaware of.
My #wrap_connect div is pretty heavily nested into the code. Do I need to have position or other attributes set on the parent items to make this work? Is there some basic gotcha that I am missing here?
Thanks for any help.
Edit: adding some minimal code. Here is the click function.
$(document).on('click', '#slink', function() {
var d = $('#wrap_connect');
d.scrollTop(d.prop("scrollHeight"));
alert('height: '+d.prop("scrollHeight"));
});//end function
As stated above, the #wrap_connect container does exist – this function returns the height of the content in the alert.
Create element with children inside using appendChild()
I am trying to create a grid layout, where by pressing the button “NEW TARGET”, a new target is created besides it. The target is everything in the lightgrey box, both the red boxes and the text saying layout: x by x. The problem I am having is that I don’t know how to create a new target with all the children inside.
<!doctype html>
<html>
<head>
<title>This is the title of the webpage!</title>
<link rel="stylesheet" type="text/css" href="Gasflasker udvidet.css" />
</head>
<body>
<div id="target-wrapper" class="target-wrapper">
<div class="target">
<p class="archive-title">Layout:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
by
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</p>
<div class="image" draggable="true">1</div>
<div class="image" draggable="true">2</div>
<div class="image" draggable="true">3</div>
<div class="image" draggable="true">4</div>
<div class="image" draggable="true">5</div>
<div class="image" draggable="true">6</div>
<div class="image" draggable="true">7</div>
<div class="image" draggable="true">8</div>
<div class="image" draggable="true">9</div>
</div>
</div>
<button id="button" class="button" onclick="newTarget()">NEW TARGET</button>
</body>
</html>
<script src="./Gasflasker udvidet.js"></script>
.target-wrapper {
background-color: black;
display: flex;
width: fit-content;
grid-gap: 10px;
align-items: center;
padding: 10px;
}
.target {
background-color:lightgrey;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
width:fit-content;
grid-gap: 5px;
padding: 5px;
}
.archive-title {
grid-column: 1/4;
}
.image {
background-color: coral;
width: 100px;
height: 100px;
}
.button {
width: 100px;
height: 100px;
}
function newTarget() {
const targetWrapper = document.getElementById("target-wrapper");
const target = document.createElement("div");
target.classList.add("target");
targetWrapper.appendChild(target);
};
I tried using appendChild(), but that only lets me create the grey box itself, not it’s children as well (at least as far as I know).
Thank you in advance!
Rollup alias fails after moving to Rollup 3
So this is the part inside the rollup.config.js that worked fine under Rollup 2 an rollup-plugin-import-alias :
alias({
Paths: {
'myfuncs': './src/js/node_modules/mylib/src/js/myfuncs',
},
}),
After updating to Rollup 3 and @rollup/plugin-alias I’m using this:
alias({
entries: [
{ find: 'myfuncs', replacement: './src/js/node_modules/mylib/src/js/myfuncs' },
]
}),
and getting this:
[!] Error: Could not load ./src/js/node_modules/mylib/src/js/myfuncs/
(imported by ../../../../d:/Dropbox/src/js/components/staticfunc.js):
EISDIR: illegal operation on a directory, read Error: Could not load
./src/js/node_modules/mylib/src/js/myfuncs/ (imported by
../../../../d:/Dropbox/src/js/components/staticfunc.js): EISDIR:
illegal operation on a directory, read
The /src/js/ folder is a virtual folder lying in my Dropbox, but that did no trouble in Rollup 2.
Did I misunderstand something about entries? Because in the alias documentations, Paths are no longer found.
Can we connect to multiple group Id in kafkajs
We have our kafka consumer application where we have one consumer group and it gets connected to multiple topics using kafkajs node js library
const consumeMessages = async () => {
const consumer = kafka.consumer({ groupId: 'test-group' })
await consumer.connect()
await consumer.subscribe({ topic: 'test-topic', fromBeginning: true })
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
value: message.value.toString(),
})
},
})
}
We want to change this approach where we want to have one consumer group for one topic . like if we have 5 topics we will have 5 consumer groups . In this case how to connect to multiple group Ids
if i do it like this
const consumer = kafka.consumer({ groupId: 'test-group' },{ groupId: 'test-group1' } ,{ groupId: 'test-group2' })
its not connecting and throwing error , cannot connect to broker .
Any idea how to achieve this
Function using interface’s generic type does not infer function typing properly
I’m overwriting the Cypress within function so that if a certain command exists before it in a chain, the within callback takes an extra parameter. This is working, but I’m having trouble getting the Typescript generic typings right.
My index.d.ts:
declare global {
export namespace Cypress {
export interface Chainable<Subject = any, Shorthand extends (object | undefined) = undefined> {
within(
fn: (currentSubject: Subject, navigationShorthand: Shorthand) => void
): Chainable<Subject, Shorthand>
within(
options: Partial<Loggable>,
fn: (currentSubject: Subject, navigationShorthand: Shorthand) => void
): Chainable<Subject, Shorthand>
}
}
}
It seems like for some reason, when I use the .within method, it isn’t picking up the generic from the outer layer. I don’t have any errors in my index.d.ts, but vscode intellisense looks like this when I mouseover the .within(...):

It looks like it knows that Shorthand should be StickyRow, but isn’t narrowing the function type. Any idea why?
Saved li data to browser not loading, only clearing
I have inputs that create li’s. Based on the two options users have (month / week), the dates on the titles of the input fields change to reflect the appropriate week of the year.
I am having trouble getting the data save and reload when the same option is reselected. Say I choose “January – Week 1” and enter “Hello”. When I switch to February, any week, all data is erased. I wanted data to clear so there would be a fresh entry space when a new option was selected, but I also wanted the entries to be saved to their particular option choices. Right now, only clearing seems to be occurring.
Here is the HTML for one of the day entries:
<div class="day scrollable" id="monday"> <div class="span"><h3 class="day-title" data-day="1">Monday</h3></div> <input type="text" class="input"> <button> <img src="/Images/plus.png" id="add-button"> </button> <ul class="list"></ul> </div>
And here is the Javascript I’ve been trying to get my desired result:
`const saveData = () => {
const dayElements = document.querySelectorAll('.day');
const data = {};
dayElements.forEach(dayElement => {
const month = document.getElementById('select-month').value;
const week = document.getElementById('select-week').value;
const dayIndex = dayElement.getAttribute('data-day');
const key = `${month}-${week}-${dayIndex}`;
const liElements = dayElement.querySelectorAll('li');
const values = Array.from(liElements).map(li => li.innerHTML);
data[key] = values;
});
localStorage.setItem('scheduleData', JSON.stringify(data));
};
const loadData = () => {
const savedData = JSON.parse(localStorage.getItem('scheduleData')) || {};
const month = document.getElementById('select-month').value;
const week = document.getElementById('select-week').value;
const data = savedData[`${month}-${week}`] || {};
const dayElements = document.querySelectorAll('.day');
dayElements.forEach(dayElement => {
const dayIndex = dayElement.getAttribute('data-day');
const key = `${month}-${week}-${dayIndex}`;
const values = data[key];
if (values && values.length > 0) {
values.forEach(value => {
let li = document.createElement('li');
li.innerHTML = value;
dayElement.querySelector('ul').appendChild(li);
let span = document.createElement('span');
span.innerHTML = "u00d7";
span.addEventListener('click', (e) => {
e.stopPropagation();
e.target.parentElement.remove();
checkScroll();
saveData();
});
li.appendChild(span);
li.addEventListener('click', () => {
li.classList.toggle('checked');
});
});
}
});
};
const clearData = () => {
const month = document.getElementById('select-month').value;
const week = document.getElementById('select-week').value;
const dayElements = document.querySelectorAll('.day');
dayElements.forEach(dayElement => {
const dayIndex = dayElement.getAttribute('data-day');
const key = `${month}-${week}-${dayIndex}`;
if (dayElement.querySelector('ul').getAttribute('data-key') === key) {
dayElement.querySelector('ul').innerHTML = '';
} else {
// Clear the li elements for other months and weeks
dayElement.querySelector('ul').innerHTML = '';
dayElement.querySelector('ul').setAttribute('data-key', key);
}
});
saveData();
};
selectMonth.addEventListener('change', () => {
clearData();
loadData();
updateDayTitles();
});
selectWeek.addEventListener('change', () => {
clearData();
loadData();
updateDayTitles();
});
updateDayTitles();
});`
Any help would be appreciated. Thank you
Javascript promise not resolved as expected
I am using a Javascript library called ATS (Authenticated Traffic Solution). I am not sure if this is the right title for my issue but I am getting an unexpected value from a method returning either a promise or a concrete value if a callback is defined.
The method is the following:
ats.retrieveEnvelope(callback);
Fetch the envelope from configured storage; the callback function is optional. If the function is called without a callback, a promise will be returned. If the function is called with a callback, an envelope value will be returned.
Also from the docs I know that the returned envelope should be of the form:
{
"envelope:"sdfasdfasdfa"
}
This is how I am using it in my code then
updateSomething(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.loadEnvelope()
.then(updatedOrNewEnvelopeWrapper => {
this.sendSync(updatedOrNewEnvelopeWrapper);
resolve();
})
.catch(error => {
console.error(`Error while retrieval ${error}`);
reject(error);
});
});
}
private loadEnvelope(): Promise<string> {
return retryPromise<string>(
() =>
new Promise<string>((resolve, reject) => {
if (this.ATSOnPage()) {
try {
resolve(this.getFromATS());
} catch (error) {
console.error('Some error');
reject(error);
}
} else {
reject(new Error('Some other error'));
}
}),
this.maxATSRetrievalRetries,
this.retryDelay
);
}
private getFromATS(): string {
return this._window.ats.retrieveEnvelope(function (envelope: string) {
return JSON.parse(envelope).envelope;
});
}
The value of updatedOrNewEnvelopeWrapper is always
{
"envelope": "fasdfasdf"
}
while I would expect for the JSON to have been successfully parsed under getFromATS, so updatedOrNewEnvelopeWrapper would have been just the string fasdfasdf.
I changed the getFromATS like so:
private getFromATS(): string {
return this._window.ats.retrieveEnvelope(function (envelope: string) {
console.log('Located ATS.js');
var parsed = JSON.parse(envelope);
while ('envelope' in parsed && typeof parsed.envelope == 'object') {
parsed = parsed.envelope;
}
if ('envelope' in parsed && typeof parsed.envelope == 'string') {
if (parsed.envelope.includes('envelope')) {
console.log(`JSON string is ${parsed.envelope}`);
const jsonString = JSON.parse(parsed.envelope);
return jsonString.envelope;
} else return parsed.envelope;
} else throw new Error('Malformed ATS response');
});
}
}
so that it can check arbitrarily deep in the json struct to find the final envelope value, since I thought that maybe the return value would be
{
"envelope": {
"envelope":{
"envelope":"asdfasdfasdf"
}
}
}
I also though that the envelope would be a json string itself like:`
{
"envelope": '{"envelope":"asdfasdfa"}'
}
Nevertheless, I am still getting the value of updatedOrNewEnvelopeWrapper as {"envelope":"asdfasdfa"}
Can you spot the bug?
Modding game, JavaScript not working and seemingly no problem
I have found a game called “Progress Knight”. I have beaten the game and want to add more content, and I have currently added a heavenly path as well as some more skills. When I open the game, the game script does not run and the whole thing is broken. The inspect element console simply says something like “cannot read null” or smth like that.
Here are the game files linked.
main.js
ExpandedKnight.html
the actual game
I tried adding my additions to the “job/item/skill categories”, “items/skills/jobs”, and “tooltips” groups in the game script. I then added requirements for my items, but now it doesn’t work and says that it can’t read null, when there is something there.
Choosing a dependency injection library
I’m having trouble using a dependency injection library with React Native, all the packages I found are out of date (inversify, tsyringe, typescript-ioc) and @nestjs doesn’t work well in React Native (at least in my experience).
Does anyone know why no one is updating these kinds of libraries?
Is there a better solution to inject dependencies without going through libraries?
I’m thinking of using typedi but I don’t know if this will be a problem in the future.
How to loop through slides and not show empty slide?
I have a slider, it loops fine through the slides until certain point when it displays an empty element
`
<script>
var slideIndex = 0;
showSlide(slideIndex);
function showSlide(index) {
var slides = document.getElementsByClassName("slide");
var prev = document.querySelector(".prev");
var next = document.querySelector(".next");
if (index >= slides.length) {
slideIndex = 0;
} else if (index < 0) {
slideIndex = slides.length - 1;
} else {
slideIndex = index;
}
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex].style.display = "flex";
}
function plusSlide(n) {
showSlide(slideIndex + n);
}
var prev = document.querySelector(".prev");
prev.addEventListener("click", function() {
plusSlide(-1);
});
var next = document.querySelector(".next");
next.addEventListener("click", function() {
plusSlide(1);
});
</script>
`
it shows an empty element at when its done showing all the slides when clicking on the prev or next button.
Load Kendo UI Grid Data into HiddenFor field via Javascript
I have a Kendo UI grid that I’m building dynamically in javascript
@(Html.Kendo().Grid<SelectListItem>()
.Name("projectGrid")
.Columns(columns => {
columns.Bound(column => column.Text).Title("Project Code").Width(500);
columns.Bound(column => column.Value).Title("Miles");
columns.Command(column => {
column.Destroy();
});
})
)
—
$('#addProjectRow').click(function () {
var projectCode = $('#addProjectGroupCode').data("kendoDropDownList").text();
var projectMiles = $('#projectMiles').val();
var newGridRow = { Text: projectCode, Value: projectMiles };
$('#projectGrid').data("kendoGrid").dataSource.add(newGridRow);
$('#addProjectGroupCode').data("kendoDropDownList").value(-1);
$('#projectMiles').val('');
});
I need to add the data from the grid to a HiddenFor field (which is a List) so that it can POST as part of the Model on POST.
@Html.HiddenFor(m => m.GroupList)
I have a javascript function to collect data before post. Here is where I want to populate the above HiddenFor field.
function NewMileageCollection() {
var sDate = $('#addDate').data("kendoDatePicker").value();
var empId = $('#addEmployeeName').data("kendoDropDownList").value();
var usageDate = kendo.toString(sDate, "MM/dd/yyyy");
var vehCode = $('#addVehicleCode').data("kendoDropDownList").text();
var sMiles = $('#startMile').val();
var eMiles = $('#endMile').val();
var tMiles = $('#totalMile').val();
$('#VehicleCode').val(vehCode);
$('#EmployeeId').val(empId);
$('#MileageUsageDate').val(usageDate);
$('#StartMiles').val(sMiles);
$('#EndMiles').val(eMiles);
$('#TotalMiles').val(tMiles);
var grid = $('#projectGrid').data('kendoGrid');
var gridData = grid.dataSource.data().toJSON();
$.each(gridData,
function (i, v) {
$('#GroupList').append('<option value="' + v.value + '">' + v.text + '</option>');
});
}
I’ve attempted many things, but the field always has 0 records.
[Highcharts][Datatables]Total in title
I am using Datatables to feed a simple pie Highcharts.
It is working well, but I would like to include the total number in the title.
[This example][1] explains how to add the total number in the subtitle of a donut, which is not far from what I am aiming at.
There are as well a couple of Stackoverflow cases like [this one][2] or [that one][3] and [this][4] is a working example with the total in the top left corner.
Do you know how I could combined those so the total number is part of the title?
[1]: https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/donut-race
[2]: Total of values in HighCharts Pie Chart
[3]: HighCharts : Total Value is not showing in Pie Chart
[4]: https://jsfiddle.net/BlackLabel/o4bx6139/1/
Raw body verification in stripe
I am trying to access the raw body in Fastify for verification in Stripe. But, I am not able to do it in any way. I tried most of the solutions mentioned here.
This is how I am registering the controller to routes.
export const paymentRoutes = (app: FastifyInstance, _opts: any, done: Function) => {
app.register(rawbody, {
field: 'rawBody',
global: false,
encoding: 'utf8',
runFirst: true,
});
app.route({
method: ['GET', 'POST'],
url: '/webhook',
config: {
rawBody: true,
},
handler: subscriptionWebhook,
});
})
And this is how I am instantiating fastify server.
export default class App {
public app: any;
public port: number;
constructor(port ? : number) {
this.app = fastify({
querystringParser: (query: string) => qs.parse(query),
});
this.port = port || config.app.port;
this.setup();
}
public setup() {
this.app.register(helmet);
this.app.register(cors, {
credentials: true,
origin: ['https://localhost:3000'],
'Access-Control-Allow-Origin': true,
'Access-Control-Allow-Methods': 'PUT,GET,POST,DELETE,PATCH',
});
//Content Parser : that I cannot remove from every route. Is there any way to add 2 different parsers one on specific route and other one on rest of the routes
this.app.addContentTypeParser(
'application/json', {
parseAs: 'string',
bodyLimit: 120000000
},
(_: any, body: any, done: any) => {
try {
const json = JSON.parse(body as string);
done(null, json);
} catch (e: any) {
e.statusCode = 400;
done(e);
}
},
);
}
stripe.webhooks.constructEvent(body, sig, endpointSecret);
I tried passing rawBody and body but it is always throwing me this error.
reason: StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
How to change the last character of string? [duplicate]
Here’s my problem:
let a = "abcd2";
a[a.length - 1] = "0";
console.log(a);
the output is still “abcd2”, but I want it to be “abcd0”, this code isn’t working, what should i do?
I also tried to use slice(-1) to get last character of string, but it shows error: ‘Uncaught ReferenceError: Invalid left-hand side in assignment’