Anyone knows how to run javascript in the WebView2 control in WinForms .NET 6.0

WebBrowser, the control that was previously used, is now deprecated as it was using IE, WebView2 uses Edge Chromium, but in WebBrowser you could call the DOM directly in C# so if I just wanted to get the content of a specific I could do it using C# code. Here you need to run the command ExecuteScriptAsync from a WebView2 instance. Nothing worked so far. I recreated new projects and tried while only doing that, still not working.

Also ExecuteScriptAsync().RunSynchronously(); didn’t work for me either.

How to detect or btter get noticed, if a font ist not only loaded but also ready to use in javascript?

The Problem: the font-loaded fires, when the font is loaded and visible, but still not full calculated?

The mission is to create an hr like element, that spreads a given pattern over a given width of an element. I named it Garnish

The easiest is eg. “+”, put as many “+” into the element (and stretch to fit)

There are more complex patterns like “(—+—)”, but this we do not need here.

All this with decorative fonts.

The logic – at least for on character – is simple. Get the width of one … the rest is clear.

This all makes more sense with decorative Fonts that have special nice looking glyphs.

So I have to wait until the font is loaded and after that I call (again) Garnish.calculate_into(element), as soon I get noticed, that the font was loaded. For this I use the FontFace interface.

All this works – most of the time for most of fonts. But not always.


The point, the problem is, that I get wrong dimensions for the glyph when I call Garnish.calculate_into(element), when call directly after “loaded

If I defer (setTimeout) this call again for up to 3 seconds, all is nice again.

Therefore I think, that loaded is not ready to use.

After I get the loaded info, the font is correct displayed. But the width of the glyph is still wrong!

3secs (or what ever time >2.5 secs) later, I get the correct width.


I try to explain step by step

We assume the pattern “+” will get “∰” after the Font is loaded.

After reloading the page I see “++++++++++” and calc_into says pattern is 5px wide (as expected)

After font loaded I see “∰∰∰∰∰∰∰∰∰∰” and calc_into says pattern is 5px wide (surprise)

If I fire calc_into 3 seconds later I see “∰∰∰∰∰∰” and calc_into says pattern is 12px wide (as expected)

This does – as expected – not happen, if Cache is not disabled.

This belongs to all browsers I can test (ie. no idea about safari).

So I think there is a difference between loaded and “ready”

Is is possible to get this ready state?

I am not searching for workarounds.

Reorder HTML elements – most efficient vs practical way

I am implementing an UI list of items. It supports ordering by sort functions and custom drag and drop ordering.

It will be used for displaying hundreds of items.

I am looking for the “best” way to implement the ordering.

Sorting is always done on data model in memory and is then projected onto the UI.

First solution I know about is just reorder the DOM elements. Simple, but it feels like a little too resource heavy…

…in comparison with flexbox and css order. That is the second solution I have in mind. Assign order with increasing values and let css do its magic… hopefully with less resources used.

The problem with css order is that if I remove or add list items, it does not reindex (the order value) automatically, so there is more maintenance to keep the system working as opposed to using DOM element order.

Do you see any (dis)advantages with using either of those?
Do you agree that using css order is (significantly) faster/less expensive?
Any other options to order elements?

How to insert selected SVG elements in a group with javascript

I am creating some svg elements with javascript, e.g.

const svg = document.querySelector('svg');

// variable for the namespace 
const svgns = "http://www.w3.org/2000/svg"

//assigning svg element attribute 
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('width', '400');
svg.setAttribute('height', '200');
svg.setAttribute('viewBox', '0 0 400 200');

//make background
var fill1 = '#e6e6e6';
//var fill2 = 'transparent';

let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('width', '200');
bg.setAttribute('height', '200');
bg.setAttribute('fill', fill1);

// append the new rectangle to the svg
svg.appendChild(bg);

function createRect(a) {

    //create element
    var rect1 = document.createElementNS(svgns, 'rect');
    rect1.setAttribute('class', 'cl' + a);
    rect1.setAttribute('id', 'id' + a);
    rect1.setAttribute('x', '10');
    rect1.setAttribute('y', '20');
    rect1.setAttribute('width', '30');
    rect1.setAttribute('height', '30');
    //rect1.setAttribute("rx", "20");
    rect1.setAttribute('fill', 'red');

    svg.appendChild(rect1);
};

//create an array from  1 to 5
var bigArray = [];
for (var i = 0; i < 5; i++) {
    bigArray[i] = i + 1;
};

//create Rect for each element of the array
for (const el of bigArray) {
    createRect(el);
}

//create group
var group = document.createElementNS(svgns, 'g');
group.setAttribute('class', 'allRect');
group.setAttribute('id', 'allRect');

svg.appendChild(group);

var x = document.querySelectorAll('[class^=cl]');
<!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">
    <title>Document</title>
</head>

<body> 
    <svg>        
    </svg>
</body>

</html>

How can I ask javascript to insert a custom selected elements document.querySelectorAll('[class^=cl]') (all 5 Rects) in a group allRect

Does Array.map() use an iterator as constructor?

This is normally a detail that is hidden from the programmer, but as a test I made a new class Vector extending Array that changed the constructor to unpack an input array and now Vector.map() stopped working:

class Vector extends Array {
    constructor(array) {
        console.assert(Array.isArray(array),
            `Vector constructor expected Array, got ${array}`);
        // ignore special case of length 1 array
        super(...array);
    }

    add(other) {
        return this.map((e, i) => e + other[i]);
    }
}

let a = new Vector([1,2,3]);
console.log(a.add(a));

I assume what happened based on my Python experience is that Array.map() internally constructs a new Array with an iterator, like that of Array.prototype[@@iterator](), but my Vector constructor instead takes an Array object. Is this correct? Maybe map is a primitive of the JS implementation.

The Odin Project – Fundamentals 05 – sumAll

I’m stuck in the sumAll exercise from the Fundamentals portion of the Odin Project. I passed the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?

This is the exercise:

const sumAll = require('./sumAll')

describe('sumAll', () => {
  test('sums numbers within the range', () => {
    expect(sumAll(1, 4)).toEqual(10);
  });
  test('works with large numbers', () => {
    expect(sumAll(1, 4000)).toEqual(8002000);
  });
  test('works with larger number first', () => {
    expect(sumAll(123, 1)).toEqual(7626);
  });
  test('returns ERROR with negative numbers', () => {
    expect(sumAll(-10, 4)).toEqual('ERROR');
  });
  test('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, "90")).toEqual('ERROR');
  });
  test('returns ERROR with non-number parameters', () => {
    expect(sumAll(10, [90, 1])).toEqual('ERROR');
  });
});

My code:

const sumAll = function(...args) {
    if(!isNumeric(args) || !checkPositive(args)){
        return "ERROR";
    }
    else{
        args.sort();
        let result=0;
            for(let i=args[0]; i<=args[1]; i++){
                result += i;
            }
            return result;
        }
};
//check for +ve numbers
function checkPositive(arr){
    return arr.forEach(element =>{
        if(element>0){
            return true;
        }
        else{
            return false;}
    });
}
//check for numeric values
function isNumeric(arr){
    return arr.forEach(element =>{
        if(typeof element == "number"){
            return true;
        }
        else{
            return false;}
    });
}
module.exports = sumAll;

    enter code here

Changing button style after interaction using Discord.js v13

I’m trying to make a rock paper scissors game using buttons, however, I’m new to 13v and this is my first time using buttons, I wanted to make it where when the user clicks the button of their choice, that button turns green aka its style turns into “SUCCESS” but it’s not updating on the Discord API, seems like styles aren’t Read-only so, does anyone have any idea why is this happening?

My code:


const db = require('quick.db')
const { MessageEmbed, MessageButton, MessageActionRow } = require('discord.js')
const { BOT_PREFIX } = require('../config')
const commandName = 'rockpaperscissor'


module.exports = client => {
    client.on('messageCreate', async message => {
        if (message.author.bot) return
        if (!message.content.startsWith(BOT_PREFIX)) return

        const command = message.content.split(' ')
        const args = message.content.substring(1).split(' ')

        if (command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith(commandName) || command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith('rps')) {
            const buttonRow1 = new MessageActionRow().addComponents(
                new MessageButton()
                .setCustomId('rock')
                .setLabel('ROCk')
                .setStyle('SECONDARY')
                .setDisabled(false),
                new MessageButton()
                .setCustomId('paper')
                .setLabel('PAPER')
                .setStyle('SECONDARY')
                .setDisabled(false),
                new MessageButton()
                .setCustomId('scissors')
                .setLabel('SCISSORS')
                .setStyle('SECONDARY')
                .setDisabled(false)
            )
            
            const filter = (interaction) => {
                if (interaction.user.id === message.author.id) return true;
                interaction.reply({ content: 'This game isn't for you.' })
            }

            const collector = message.channel.createMessageComponentCollector({
                filter,
                max: 1,
            })

            message.reply({ content: 'Testing!', components: [buttonRow1] })
      
            const choices = ['Rock', 'Paper', 'Scissors']
            let botChoice = choices[Math.floor(Math.random() * choices.length)];

            let userBalance =  parseInt(await db.fetch(`${message.author.id}.balance`))
            if (userBalance == null) userBalance = 0
            function randomNumber(min, max) {
                return Math.floor(Math.random() * (max - min+1)+min);   
            }
            let reward1 = randomNumber(153, 535)
            function randomNumber(min, max) {
                return Math.floor(Math.random() * (max - min+1)+min);   
            }
            let reward2 = randomNumber(553, 1460)
    
            collector.on('end', async (buttonInteraction) => {
                const interaction = buttonInteraction.first()
                if (interaction.customId == 'rock') {
                    if (botChoice == 'Rock') {
                        interaction.reply({ content: `I chose Rock too, so it's a tie!nYou got `$${reward1}` as a small reward.`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                        interaction.component.setStyle('SUCCESS')
                    } else if (botChoice == 'Paper') {
                        interaction.reply({ content: `I chose Paper, so I win!`})
                        interaction.component.setStyle('SUCCESS')
                    } else if (botChoice == 'Scissors') {
                        interaction.reply({ content: `I chose Scissors, so you win!nYou got `$${reward2}` as an award!`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                        interaction.component.setStyle('SUCCESS')
                    }
                }
            })
        }
    })
}

There is no error at all.

More Info:

Discord.js version: '^13.6.0'
Node version: '16.14.0'
npm version: '8.3.1'

How to show hidden pseudo-element with JavaScript

I’m using CSS to hide form elements:

#main_form #form-field-email, #form-field-realtor_select { display: none;}
#main_form .elementor-select-wrapper::before { display: none; }

Then JavaScript to show them with:

document.getElementById("form-field-first_name").onclick = function(){
  document.getElementById('form-field-email').style.display = 'block';
  document.getElementById('form-field-realtor_select').style.display = 'block';

The problem is with the pseudo-element “.elementor-select-wrapper::before” which is needed to hide the down arrow in the select element. I need to get the arrow to display using the JavaScript onclick event. I tried document.getElementsByClassName() but that did not work.

You can see the test page here: Test Page. Click First Name or Last Name to reveal fields (more than listed above) and you’ll see the down arrow is mission from the select element.

Content Script doesn’t run until page reload

Although there are a lot of similar questions here, I couldn’t solve my problem with any of the accepted solutions, so I’m creating a new question.

I have a content script that adds some functionality to a Jira Issue.
However, when navigating to the Jira Issue from a Filter Results Page, the content script doesn’t run until I manually reload the page.

What I’ve tried so far:

  1. Adding webNavigation Listeners (with the manifest permission), but none of them seem to trigger when the Jira Issue link is clicked from the Filter Page.
// background.js

const myLog = () => console.log('webNavigation event triggered');

browser.webNavigation.onDOMContentLoaded.addListener(myLog);
browser.webNavigation.onHistoryStateUpdated.addListener(myLog);
browser.webNavigation.onReferenceFragmentUpdated.addListener(myLog);
  1. Adding “all_frames”: true to the manifest.json, but that didn’t make it work either:
// manifest.json

...

"background": {
    "scripts": ["background.js"],
    "persistent": false
  },
"content_scripts": [
    {
      "matches": ["*://jira.atlassian.com/*"],
      "js": ["content.js"],
      "all_frames": true
    }
  ],
"permissions": ["tabs", "webNavigation", "<all_urls>"]
  1. Listening to window.onpopstate event inside the content script. Although it detects when I click the “Back” and “Forward” arrows in the browser, it doesn’t fire when I click the links inside the Filter Results Page.
// content.js

window.onpopstate = () => {
 browser.runtime.sendMessage('webNavigation event triggered');
}

How can I run this content script without having to manually reload the page?

Change BOX color depending on value – Adobe Acrobat JavaScript

I don’t have a lot of experience with programming. I did a couple of semesters of C++ and that’s about it.
This is the first time I have to use JavaScript for work.

I’m supposed to make a PDF schedule document.
The people I’m working with are technologically impaired, so I’m trying my best to make it as easy as possible to edit the document.
It’s supposed to be a PDF file schedule. The schedule should either have a

  1. Drop down menu of ONLY colours (no text) to change the box into another colour
    example (no text)

or

  1. Depending on the text you put in the box will change the colour.
    I’ve tried doing this with the form options that Acrobat has available, but it’s impossible. I could make a text drop down menu, but I can’t do anything with the colour of the box. example (keep text)

I thought Java would be the best option.

I am trying to create a button that scrolls to the next section. How can I track current section being viewed and manage with state?

I am trying to create a button that scrolls to the next section of the page regardless of the current section and how a user has gotten there.
(Currently, the button goes to the next section, but if the user scrolls to a new section by scrolling and not clicking the button, the current section is not updated and clicking the button will lead to the wrong section).

How can I track the current section being viewed when a users scrolls to access it and when the button is clicked? I currently have a React app that renders a number of components all at once. Each component is a section, all of which are held in a container div. Each section is 100vh (like a new page) and I would like to go to a new page when clicking the button or scrolling.

the current code is below:

const [currentSection, setCurrentSection] = useState(1)

const sections = {
1 : '#home',
2 : '#two',
3 : '#three',
4 : '#four',
5 : '#five'

};

…inside of the return

    {currentSection <= 5 &&

    <div className='scroll-down'>
        <a href={`${sections[currentSection]}`} onClick={() => setCurrentSection(currentSection + 1)}>
        <button id="btnScroll" >
          <i className='material-icons'>arrow_downward</i>
        </button>
        </a>
    </div>
    }

  <div className='container'>
    <Home/>
    <Philosophy/>
    <Experience/>
    <Projects/>
    <Contact/>
  </div>

Typing in the firt input without focusing

I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers

My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers

const maxLength = 7;
const firstInput = document.querySelector("#pin"); 
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")

let activeInput;

firstInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
  console.log("i'm changing!");
  if (firstInput.value.length >= maxLength) {
    activeInput = secondInput;
    secondInput.focus();
  }
});


secondInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
  // manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
  activeInput.dispatchEvent(changedEvent);
}
    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>
    <br />
        <input type="text" id="pin" />
        <input type="text" id="key" />

How to turn a string into class in typescript?

I have a class CustomError defined like so;

import IError from "../interfaces/IError";
import { StatusCodes } from "http-status-codes";

export default class CustomError implements IError {
      constructor(
            public message: string = "Something went wrong",
            public status_code: number = StatusCodes.INTERNAL_SERVER_ERROR,
            public name: string = "internal_error",
            public render?: boolean,
            public stack?: string | undefined
      ) {}
}

and an enum Err defined as follow;

enum Err {
      unauthorized = "UnauthorizedError",
      custom = "CustomError",
      notFound = "NotFoundError",
      badRequest = "BadRequestError",
}

how can i turn Err.custom for example into the class CustomError.

Is it possible to export to body of two different files from main.js?

I want to export components to multiple files from main.js, something like this:

main.js:

import Block1 from './Block1.svelte';
import Block2 from './Block2.svelte';

export const Block1  = new Block1({ target: document.body}); //to index.html 
export const Block2  = new Block2({ target: document.body}); //to index2.html 

How to compile multiple .html files to public directory in svelt js?

Divi – Slide Navigation On Button Optimisation

I have a slide navigation script that allows me to navigate to a particular slide using an “nth-child(#) that triggers a click event.

Each button currently has its own slide reference, i.e Slide-1 button will link to nth-child(1) and so forth through to slide/button 8

I am looking for ways to optimise the below script using a loop or something similar so that it is more manageable and still keeps the same functionality.

<script>
  
jQuery(document).ready(function( $ ) {
  
var selector = '.activelinks a';
$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});
  
$("#Slide-1").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(1)").trigger("click");
});
    
$("#Slide-2").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(2)").trigger("click");
});
    
$("#Slide-3").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(3)").trigger("click");
});
    
$("#Slide-4").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(4)").trigger("click");
});
  
$("#Slide-5").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(5)").trigger("click");
});
    
$("#Slide-6").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(6)").trigger("click");
});
    
$("#Slide-7").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(7)").trigger("click");
});
    
$("#Slide-8").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(8)").trigger("click");
});
});
</script>