How to hide menu items on mobile when clicked

I’m working on a one-page WordPress website and the page scrolls to each section when a menu item is clicked. It works well on desktops/laptops but on mobile devices when the hamburger menu is tapped, the menu opens and it blocks the screen. I would like to hide the dropdown menu list/section only on mobile. At the moment I have to close the menu by tapping on “X” close button.

I have searched for a solution and I found some JS code here in Stackoverflow but it has not worked.

Here is the JS code:

<script>
  function closeFunction()
  { 
     document.getElementById('bs-example-navbar-collapse-1').style.display='none';
  }
</script>

I’m not so experienced in JS but with some guidance I fix this, please help.

Screens:
enter image description here

Not receiving data or props when using State in Link and printing on another page/jsx file

I am sending my props using state in from ContactCard to ContactDetails Page. But when using useLocation hook, i am receiving null in Location.state.

ContactCard.jsx

import React from 'react';
import { Link } from 'react-router-dom';

const ContactCard = (props) => {
  const { id, name, email } = props.contact;

  const removeId = (id) => {
    props.getDeleteId(id);
  }

  return (
    <>
      <div>
        <Link
          to={{ pathname: `/ContactDetails/${id}` }}
          state={props.contact}
          style={{ cursor: "pointer" }}
        >
          <i className="bi bi-person-circle"></i>
          <label className='p-1'>{name}</label>
          <label>{email}</label>
        </Link>
        <i
          className="bi bi-trash ml-10"
          onClick={() => removeId(id)}
          style={{
            cursor: "pointer",
            color: "red",
            marginLeft: "48px"
          }}
        ></i>
      </div>
      <div className='ul'></div>
    </>
  );
}

export default ContactCard;

ContactDetails.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

const ContactDetails = () => {
  const location = useLocation();
  const { contact } = location.state || {};

  if (!contact) {
    return <div>No contact data available.</div>;
  }

  console.log(contact);

  return (
    <>
      <div>
        <div>{contact.name}</div>
        <div>{contact.email}</div>
      </div>
      <div className='ul'></div>
    </>
  );
};

export default ContactDetails;

Data in props.contact:

{
  id: 'ec49b94a-eebf-4111-8e7e-40ea1a72a92e',
  name: 'abc',
  email: '[email protected]'
}

I should be able to receive the props.contact data in location.state.

How to run Typescript code with npm packages in Unity?

I want to run my ts file which uses a npm package in Unity. Is there any way to do that?

Also required tsconfig compiler settings:

{
    "compilerOptions": {
        "target": "es2020",
        "module": "es2022",
        "lib": ["dom", "esnext"],
        "outDir": "./build",
        "rootDir": ".",
        "strict": true,
        "strictPropertyInitialization": false,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "esModuleInterop": true,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "allowJs": true,
        "declaration": true,
        "sourceMap": true,
        "noFallthroughCasesInSwitch": true,
        "allowSyntheticDefaultImports": true
    },
    "include": ["./src"]
}

Filterable DIV Won’t ‘Show All’ Until Button Clicked

I am using the “Filter Elements” example from W3Schools for a page template so that the visitor can filter listings based on the number of bedrooms. The filter buttons are working correctly, however when you first load the page all of the listings are hidden. The “Show All” button is active, like in the W3Schools example, however you still have to click “Show All” before it will load the hidden content.

Here is the W3Schools example: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements

Here is my test page with the issue: https://lakewoodcampground.com/properties-test-page/

I need the page to load with all of the listings visible. Essentially starting with the “Show All” button active, which it is, but on page load the listings are hidden.

<div id="myBtnContainer">
  <button class="btn active" onclick="filterSelection('all')"> Show all</button>
  <button class="btn" onclick="filterSelection('one-bed')"> 1 Bedroom</button>
  <button class="btn" onclick="filterSelection('two-bed')"> 2 Bedroom</button>
  <button class="btn" onclick="filterSelection('three-bed')"> 3 Bedroom</button>
  <button class="btn" onclick="filterSelection('four-bed')"> 4 Bedroom</button>
  <button class="btn" onclick="filterSelection('five-bed')"> 5 Bedroom</button>
</div>
<script>
    filterSelection("all")
    function filterSelection(c) {
      var x, i;
      x = document.getElementsByClassName("filterDiv");
      if (c == "all") c = "";
      for (i = 0; i < x.length; i++) {
        w3RemoveClass(x[i], "show");
        if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
      }
    }

    function w3AddClass(element, name) {
      var i, arr1, arr2;
      arr1 = element.className.split(" ");
      arr2 = name.split(" ");
      for (i = 0; i < arr2.length; i++) {
        if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
      }
    }

    function w3RemoveClass(element, name) {
      var i, arr1, arr2;
      arr1 = element.className.split(" ");
      arr2 = name.split(" ");
      for (i = 0; i < arr2.length; i++) {
        while (arr1.indexOf(arr2[i]) > -1) {
          arr1.splice(arr1.indexOf(arr2[i]), 1);     
        }
      }
      element.className = arr1.join(" ");
    }

    // Add active class to the current button (highlight it)
    var btnContainer = document.getElementById("myBtnContainer");
    var btns = btnContainer.getElementsByClassName("btn");
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function(){
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
      });
    }
    </script>

How to display in the placeholder the exchange rate from a currency to another?

i’m new of using svelte so maybe my question could sound a little dumb, i managed to render the data that i got from the api in my code but now i would like to show in the placeholder of my input the exchange rate that i got from each currency to show the exchange rate between the 2 currencies.

i have two of these blocks because i need 2 inputs in my app so this is how should be the app, but in this way i see for each inputs the options in the selection tag, but it looks like the placeholder of the input and the selection are not linked, i mean if i select a different currency the placeholder doesn’t match with the exchange rate of that currency

{#each Object.entries(exchangeRates) as [key, value], index}
  {#if index === 0}
    <div class="input-box">
      <input type="number" min="0" id="rate1" placeholder={value} />
      <select id="option1">
        {#each Object.entries(exchangeRates) as [key, value]}
          <option value={key}>{key}</option>
        {/each}
      </select>
    </div>
  {/if}
{/each}

in this way i see an input for every currency that i have (5), but placeholder and selection are matching

{#each Object.entries(exchangeRates) as [key, value]}
    <div class="input-box">
      <input type="number" min="0" id="rate1" placeholder={value} />
      <select id="option1">
          <option value={key}>{key}</option>
      </select>
    </div>
{/each}

Any suggestion how to fix this?

Please help me to achieve full-size screenshot using my own extension in react.js

Not able to capture the screenshot of the full-size on chrome’s current activated tab!
https://github.com/adhiavraj/fullsize-ss-chrome-extension/tree/main/public i have uploaded code here. currently am not using getScrollHeight.js file so you can ignore that. There is no error by executing the build folder on extension even getting the Message received: captureAndDownloadScreenshot from the background.js file after clicking Capture Screenshot button from popup.html. Please help if anyone could! 🙂

I tried alot of debugging and found that there is something not correct with the content.js file under the public folder (have provided the git repo link).

Expectation: When i click on the Capture Screenshot Button from popup.html file which is defaultly laoded into the extension i have to capture the full-size screenshot of the webpage which is on the current acitvated tab 🙂

Please help if anyone could!

selection not getting cleared after button click

I am wondering why the selection is not getting cleared or basically switching to -No Selection- option when Clear Selection button is clicked.

$("#clearTag").select2();

document.getElementById('clear-selection').addEventListener('click', function () {
console.log("button clicked");
$("#clearTag").val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"> 
<!-- Select2 CSS --><!-- Select2 JS --> 
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div>
<select id="clearTag" name="clearTag" >
  <option value="" >-No Selection-</option>
     
      <option value="Duplicate" >Duplicate</option>
      <option value="HandwrittenNote" >HandwrittenNote</option>
      <option value="Inappropriate" >Inappropriate</option>
      <option value="Incomplete" >Incomplete</option>
      <option value="Incorrect" >Incorrect</option>
    
      <option value="NameDiscrepancy" >NameDiscrepancy</option>
      <option value="Payment" >Payment</option>
</select>

</div>

<input type="button" id="clear-selection" value="Clear Selection!">

Is using $("#clearTag").val(''); not a correct way to go about it?

Can someone check this code please? Countdown timer to deadline of 2pm but excluding weekends and UK Bank Holidays [closed]

New to this forum. I’ve been racking my brains over this for quite some time now and simply cannot get it working as I would like.

Basically, I’ve created a countdown timer which I want to reset every day at 2pm and deliver the message as below, “Order with ‘countdown’ timer to receive by ‘date'”

So where it is falling over is I cannot seem to get it to skip weekends or UK Bank Holidays and with a UK Bank Holiday this coming Monday, it would be really nice if I could get this fully tested and working.

So if someone orders today and up until 2pm tomorrow, Thursday 2nd May they will receive their item on Friday 3rd May 2024. This is working fine!

But when the time is UK 2pm GMT on Friday 3rd May, it should say “receive by Tuesday 7th May 2024”. If it WAS NOT a UK Bank Holiday this weekend, it should say “receive by Monday 6th May”.

On weekends, it should ideally count down to 2pm this Saturday and tell the customer “receive by Tuesday 7th May”. The same goes for Sunday, 5th and Monday 6th providing they order before 2pm!

On any other weekend which is not followed by a Bank Holiday, it should tell the customer this:-

  1. Before 2pm on Friday, 10th May, “receive by Monday 13th May.”
  2. After 2pm on Friday, 10th May, “receive by Tuesday 14th May.”
  3. After 2pm on Saturday, 11th May, “receive by Tuesday 14th May.”
  4. After 2pm on Sunday, 12th May, “receive by Tuesday 14th May.”
  5. BEFORE 2pm on Monday, 13th May, “receive by Tuesday 14th May.”
  6. After 2pm on Monday, 13th May, “receive by Wednesday 15th May.”
  7. BEFORE 2pm on Tuesay, 14th May, “receive by Wednesday 15th May.”

and so on.

Any pointers or super genii out there that can help me tweak the code as I have seemingly tried absolutely everything.

I won’t say I think it’s impossible because I believe nothing is impossible. It’s just beyond my skillset!!!

< script >
  // UK Bank Holidays between now and 2027
  var bankHolidays = ["2024-05-06", "2024-05-27", "2024-08-26", "2024-12-25", "2024-12-26", "2025-01-01", "2025-04-18", "2025-04-21", "2025-05-05", "2025-05-26", "2025-08-25", "2025-12-25", "2025-12-26", "2026-01-01", "2026-04-03", "2026-04-06", "2026-05-04", "2026-05-25", "2026-08-31", "2026-12-25", "2026-12-28"];

// Get today's date and time
var now = new Date();

// Set the countdown date and time to 2 PM today
var countDownDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 0, 0, 0);

// If it's past 2 PM, set the countdown date and time to 2 PM tomorrow
if (now > countDownDate) {
  countDownDate.setDate(countDownDate.getDate() + 1);
}

// Calculate the delivery day
var deliveryDay = new Date(countDownDate);
// If the order is placed up until 2 PM on Wednesday, the delivery day is Friday
// If the order is placed after 2 PM on Wednesday, the delivery day is Monday
if (deliveryDay.getDay() <= 4) {
  deliveryDay.setDate(deliveryDay.getDate() + (5 - deliveryDay.getDay()));
} else {
  deliveryDay.setDate(deliveryDay.getDate() + ((8 - deliveryDay.getDay()) % 7));
}

// If the delivery day is a bank holiday, postpone it to the next day
while (bankHolidays.includes(deliveryDay.toISOString().split('T')[0])) {
  deliveryDay.setDate(deliveryDay.getDate() + 1);
}

// Update the delivery day element
document.getElementById("deliveryDay").innerHTML = deliveryDay.toDateString();

// Update the countdown timer every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the countdown date
  var distance = countDownDate - now;

  // Time calculations for hours, minutes and seconds
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in the timer element
  document.getElementById("timer").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";

  // If the countdown is over, reset the countdown date and time to 2 PM tomorrow and recalculate the delivery day
  if (distance < 0) {
    countDownDate.setDate(countDownDate.getDate() + 1);
    if (countDownDate.getDay() <= 3) {
      deliveryDay.setDate(deliveryDay.getDate() + (5 - deliveryDay.getDay()));
    } else {
      deliveryDay.setDate(deliveryDay.getDate() + ((8 - deliveryDay.getDay()) % 7));
    }
    while (bankHolidays.includes(deliveryDay.toISOString().split('T')[0])) {
      deliveryDay.setDate(deliveryDay.getDate() + 1);
    }
    document.getElementById("deliveryDay").innerHTML = deliveryDay.toDateString();
  }
}, 1000); <
/script>
<div>
  <h3>Order within <span class="countdown" id="timer"></span> to receive *<span class="deliverydate" id="deliveryDay"></span></h3>
</div>
<div>
  <h4>*Exclusions apply. Click <a href="/despatch-delivery-information" id="deliverydaysmall">HERE</a> for full details or if your item is time critical.</h4>
</div>
<script src="https://bp215.bluepark.build/user/countdowntest.js"

Passing user data to a crawler

I have this function

async function extractFromSearchPage(url, log) {
    searchOptions = {'somevalue'}
    likelyPaginationButtonResponse = {'somevalue'}
    await searchPageCrawler.run([{
        url: url,
        userData: {
            searchOptions: searchOptions,
            paginationButton: likelyPaginationButtonResponse
        }}])

}
    

And I want to pass userData to this crawler

// Function to interact with the page using Playwright
const searchPageCrawler = new PlaywrightCrawler({
    launchContext: {
        launchOptions: {
            launcher: 'firefox',
            headless: false, // Run in head-full mode to mimic a real user
            firefoxUserPrefs: {
                'general.useragent.override': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0', // Example user agent
            },
            args: [
                '--disable-web-security', // Disables web security to prevent CORS issues
                '--disable-features=IsolateOrigins,site-per-process', // Disables site isolation
                '--blink-settings=imagesEnabled=true', // Ensures images are loaded
            ]
        },
        // stealth: true, // Use stealth plugin to prevent detection
    },
    async requestHandler({ page, request, session, log }) {
        log.info(`Starting the crawler.`);
        log.info(`Processing search page at URL: ${request.url}`);
        log.info(`Processing search page at URL: ${request.url} with details: ${JSON.stringify(session)}`);
        log.info(`Processing search page at URL: ${request.url} with details: ${JSON.stringify(session.userData)}`);
    
        await page.goto(request.url);
        await page.waitForSelector('body'); // Ensure the page has loaded
    
});

But right now session.userData shows up as empty.

INFO PlaywrightCrawler: Interacting with search page using details: {}
INFO PlaywrightCrawler: session.userData: {}
INFO PlaywrightCrawler: searchDetails: undefined

Even though the data is instantiated in extractFromSearchPage() and has a value there

Cannot read properties of undefined (reading ‘templates_empty_title’)

In WordPress, I have the following error during editing page in backend

Uncaught TypeError: Cannot read properties of undefined (reading 'templates_empty_title')
    at ElementorCommonApp.translate (common.min.js?ver=3.15.3:3:159255)
    at Editor.translate (editor.min.js?ver=3.15.3:3:568743)
    at ./assets/admin/src/template-library/LibraryTemplatesEmpty.js (elementor-modal.js:1:14611)
    at n (elementor-modal.js:1:110)
    at ./assets/admin/src/template-library/LibraryCollection.js (elementor-modal.js:1:5481)
    at n (elementor-modal.js:1:110)
    at ./assets/admin/src/template-library/LibraryLayoutView.js (elementor-modal.js:1:11415)
    at n (elementor-modal.js:1:110)
    at ./assets/admin/src/template-library/Component.js (elementor-modal.js:1:2039)
    at n (elementor-modal.js:1:110)

Could you show me how could investigate more and solve the problem
thank you in advance

i need to mock the reload method of window.location object for testing in jest

i have declared a function named as reloadScreen, which reload the browser window on execution and it gets invoked on clicking a button. Now i want to test this function that on clicking a button window is getting reloaded or not, i am testing in jest.

my html code for button is :
<button class='restartBtn' onclick="reloadScreen()">reset</button>

my javascript function is:

function reloadScreen(){
    window.location.reload();
}

my test code is provided below :

describe('should reload the browser on clicking a button having class as "restartBtn". ', ()=> {

  let restartButton;
  let dom;
  let window;
  let document;

  beforeEach(() => {
    dom = new JSDOM(html,  { runScripts: 'dangerously' });
    document = dom.window.document;
    window = dom.window;

    restartButton = document.querySelector('.restartBtn');
  })

  test('should reload the browser.', ()=>{

    // Mock the reload method of window.location object
    const reloadMock = jest.fn();
    window.location.reload = reloadMock;

    restartButton.click();

    // Expect window.location.reload to be called
    expect(reloadMock).toHaveBeenCalled();
  })

})

error i am getting is,
[error] : reload property of window.location is read-only cannot be modified.
can anyone help me, to resolve this.

Large background video for a landing page takes a while to load

I’m pretty new to html/css, and I have a portfolio website that I coded for my UX design projects, which I host through digitalocean from github files.

My landing page background is a video, and it’s a decently large video that takes up the whole screen. This obviously takes a while to load – right now it’s just embedded as a video element in html.

I’ve tried compressing it, shortening it, etc, but it still takes a while to load for other people (not me, as I’ve loaded it so many times)

I’m wondering if there’s any other way I can put this video here. I saw some things online about hosting the video somewhere else (ex. vimeo) and embedding it so it is automatically hosted somewhere else online. Would something like this work for a background video that auto plays and loops?

Is there any other place where I can host this video and have it stream to my website when users first load it?

How do most websites do this? I’ve seen plenty of landing pages for products that feature a large, high res video that loads instantly.

Thanks for the help

Difficult to understand behavior of the Promise’s catch() in Javascript

Why is removing catch() from the Promise (p2) the result running as expected but keeping catch() the flow is different? However, the catch() in the Promise (p2) is not executed. Don’t know what I’m misunderstanding…

  • removing catch() from the Promise (p2)
const onFinally_1 = () => {
    console.log('Promise settled! 1');
    i++;
};
const onFinally_3 = () => console.log('Promise settled! 3');

const p1 = new Promise((resolve, reject) => {
    resolve(1);
})
    .then(
        (res) => Promise.resolve(onFinally_1()).then(() => res),
        (err) => Promise.resolve(onFinally_1()).then(() => { throw err; })
    )
    .then((result) => console.log(result), (x) => { console.log('B'); throw x; })
    .catch((error) => console.log('=>', error))

const p2 = new Promise((resolve, reject) => {
    resolve(3);
})
    .then((result) => console.log(result))
    // .catch((error) => console.log(error))
    .then(
        (res) => Promise.resolve(onFinally_3()).then(() => res),
        (err) => Promise.resolve(onFinally_3()).then(() => { throw err; })
    )

/* [Result]
      Promise settled! 1
      3
      B
      Promise settled! 3
      ReferenceError: i is not defined...
*/
  • keeping catch() from the Promise (p2)
const onFinally_1 = () => {
    console.log('Promise settled! 1');
    i++;
};
const onFinally_3 = () => console.log('Promise settled! 3');

const p1 = new Promise((resolve, reject) => {
    resolve(1);
})
    .then(
        (res) => Promise.resolve(onFinally_1()).then(() => res),
        (err) => Promise.resolve(onFinally_1()).then(() => { throw err; })
    )
    .then((result) => console.log(result), (x) => { console.log('B'); throw x; })
    .catch((error) => console.log(error))

const p2 = new Promise((resolve, reject) => {
    resolve(3);
})
    .then((result) => console.log(result))
    .catch((error) => console.log(error))
    .then(
        (res) => Promise.resolve(onFinally_3()).then(() => res),
        (err) => Promise.resolve(onFinally_3()).then(() => { throw err; })
    )

/* [Result]
      Promise settled! 1
      3
      B
      ReferenceError: i is not defined...
      Promise settled! 3
*/

Direct update of depending fields after selection in a SAP CAP application

I’m encountering an issue while trying to update a field that depends on the selection of a business partner (in this case, it’s the customer field).

Currently, it seems that this field isn’t recognized as dependent on the business partner during the selection process. However, after pressing save, the customer field gets updated accordingly.

I’m wondering if there’s a way or an annotation I could use to update the customer field directly after selecting the business partner? If so, what would be the best approach?

I’ve replicated the problem in this GitHub repository for better understanding: https://github.com/floliver/cap-remoteentity

Any insights or suggestions would be greatly appreciated. Thank you in advance for your help!

Access local storage from non-browser environment

I am trying to access the local storage where the language of the application is set. This language determines which file is accessed in the non-browser environment.

In src, everything works fine, but how do i access it from shared/*?

src and shared are in the same folder, both are directories.

const fs = require('fs')
const path = require('path')
const localStorage = require('localStorage'); // Import localStorage module

// Define the file paths for each language
const languageFiles = {
  en: '../../src/assets/locales/en-GB.json',
  nl: '../../src/assets/locales/nl-NL.json',
  // Add more languages as needed
};
const readFile = () => {
  const language = localStorage.getItem('language') || 'en'

  const filePath = path.resolve(__dirname, languageFiles[language])
  try {
    const data = fs.readFileSync(filePath, 'utf8')
    return JSON.parse(data)
  } catch (error) {
    console.error('Error reading file:', error)
    return {}
  }
}

I have tried to use different packages, but no luck