How to make autocomplete field with RadioGroup component

I have a text field (select mode) with options in RadioGroup like below:

enter image description here

For “Service” field I can choose options from three categories. To choose an option I have to scroll down long list. That is why, I need to change text field to let give inputs and based on the inputs filter the list and show only avaialble options. Right now, I can nit give inputs, as it is in select field.

for example here I can give inputs and get related keywords:

enter image description here

I will provide code snippet, can you give any ideas how I can do that?

return (
<FormControl style={fieldStyle}>
  <TextField
    select
    data-testid={id}
    name={name}
    value={service}
    label={label}
    onChange={handleChange}
    SelectProps={{
      open,
      onClose: handleClose,
      onOpen: handleOpen,
      MenuProps: {
        style: styles.selectField,
        PaperProps: {
          style: styles.selectPaper
        },
        anchorOrigin: {
          vertical: 'bottom',
          horizontal: 'left'
        },
        transformOrigin: {
          vertical: 'top',
          horizontal: 'left'
        },
        getContentAnchorEl: null
      }
    }}
    style={styles.field}
  >
    <div style={styles.radioContainer}>
      <RadioGroup
        row
        name="services-radio-group"
        value={filter}
        defaultValue={filter}
        onChange={handleFilter}
        style={styles.radioGroup}
      >
        <FormControlLabel value={SERVICE_CATEGORIES.ALL_THE_CATHEGORIES} control={<Radio data-testid={SERVICE_CATEGORIES.ALL_THE_CATHEGORIES} />} label={formatMessage({id: 'Common.allTheCategories'})} />
        <FormControlLabel value={SERVICE_CATEGORIES.SERVICE} control={<Radio data-testid={SERVICE_CATEGORIES.SERVICE} />} label={formatMessage({id: 'Service.label'})} />
        <FormControlLabel value={SERVICE_CATEGORIES.SERVICE_TYPE} control={<Radio data-testid={SERVICE_CATEGORIES.SERVICE_TYPE} />} label={formatMessage({id: 'Service.serviceType'})} />
      </RadioGroup>
      <Divider style={styles.divider} />
    </div>
    {servicesFiltered?.map((item, idx) => (
      <MenuItem
        key={idx}
        data-testid={`Service.${item}`}
        value={item}
      >
        {formatMessage({id: `Service.${item}`})}
      </MenuItem>
    ))}
  </TextField>
</FormControl>

The goal is when I type letters, the list in chosen category should be filtered.

Mouse cursor won’t point to proper position in inline text area

Within a text box I want my cursor to be set where I click (‘mouseup’). However the cursor doesn’t change when clicking the mouse, I can only move it using the keyboard, am I somehow disabling the mouseclicks?

Here’s the snippet …

textarea.addEventListener('mouseup', function(e) {
    e.stopPropagation();
    const pos = textarea.selectionStart;
    textarea.focus();
    textarea.setSelectionRange(pos, pos);
});

If I’m not mistaken the above code should work, can anyone see where I am going wrong?

The full function code is below.

function makeEditable(element) {
    const text = element.textContent;
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.classList.add('edit-textarea');

    // Set initial height
    textarea.style.height = 'auto';
    textarea.style.height = element.offsetHeight + 'px';

    // Replace the span with the textarea
    element.parentNode.replaceChild(textarea, element);

    // Focus and select all text
    textarea.focus();

    // Handle input for auto-resizing
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = this.scrollHeight + 'px';
    });

    // Handle blur event to save the text
    textarea.addEventListener('blur', function() {
        saveEdit(this, element);
    });

    // Handle keydown event to detect Enter key
    textarea.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            this.blur();
        }
    });

    // Prevent double-click event from being triggered again
    textarea.addEventListener('dblclick', function(e) {
        e.stopPropagation();
    });

    // Allow single clicks for cursor positioning
    textarea.addEventListener('mousedown', function(e) {
        e.stopPropagation();
    });

    // Set cursor position based on click location
    textarea.addEventListener('mouseup', function(e) {
        e.stopPropagation();
        const pos = textarea.selectionStart;
        textarea.focus();
        textarea.setSelectionRange(pos, pos);
    });
}

Why is the Website Popup animation not working?

I have copied the code from a Codepen to create an animated PopUp.

The box with the text appears and forms, and when we touch it, it disappears again with the same animation as when it appeared.

The problem is that it cannot be interpreted and when I create it locally, the animation of the PopUp box does not work. I want to add a block to a WordPress site and it doesn’t show up. Firstly, I am testing a website that I am doing locally on my PC.

But it doesn’t work locally, only the text of <h1> is shown, the rest of the text is shown in the background, at a different level than <h1>.

You can run the example, which seems to work, but in Full Screen, it doesn’t work.

I have brought the same links that the Codepen has, but it does not work in any way. what am I doing wrong? How to make all the text work equally?

This is the exact code I have, I have only added the <h2> and also the content of the <p> I cannot understand why the animation does not work and why all the texts are not displayed at the same level.

Despite the response, implement the suggested changes and it still shows an error and the PopUp animation does not work. The Google console shows:

Failed to load resource: net::ERR_FILE_NOT_FOUND

.js:8 Uncaught ReferenceError: $ is not defined

for (var i = pieces - 1; i >= 0; i--) {
  $('#popup').prepend('<div class="piece" style="width:'+pieceW+'px; height:'+pieceH+'px"></div>');
};
#wrap {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background-color: #333;
    overflow: hidden;
}

#popup {
    position: absolute;
    width: 300px;
    height: auto;
    top: 50%; left: 50%;
    margin-left: -150px; margin-top: -100px; 

    -webkit-perspective: 800px;
    -webkit-perspective-origin: 50% 50px;
   perspective: 800px;
   perspective-origin: 50% 50px;    
}

.piece {
    background: rgba(95,144,222,0.5);
    float: left;
}

#popup h1 {
    position: absolute;
    text-align: center;
    width: 100%;
    height: 40px;
    top: 50%; margin-top: -20px;    
    font-family: 'Noto Sans', sans-serif;
    color: #ccc;
}

.reverse {
    position: absolute;
    top: 30px;
    left: 50%;
    margin-left: -30px;
    font-family: 'Noto Sans', sans-serif;
    color: #ccc;
    cursor: pointer;
}

  <div id="wrap">
    <div id="popup">
        <h1>Bienvenidos de nuevo</h1>
        <h2>Hoy traemos cosas nuevas</h2>
        <p>Disculpa la espera </pp>
        <p>¡¡Nos vemos pronto con muchas sorpresas!!</p>
    </div>  
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
var pieces = 70,
    speed = 1,
    pieceW = 30,
    pieceH = 30;


for (var i = pieces - 1; i >= 0; i--) {
  $('#popup').prepend('<div class="piece" style="width:'+pieceW+'px; height:'+pieceH+'px"></div>');
};

function breakGlass(from){
  if (from === "reverse"){
    $('.piece').each(function(){
      TweenLite.to($(this), speed, {x:0, y:0, rotationX:0, rotationY:0, opacity: 1, z: 0});
      TweenLite.to($('#popup h1'),0.2,{opacity:1, delay: speed});
    });
    return;
  }

  if(!from){
    TweenLite.to($('#popup h1'),0.2,{opacity:0});
  } else {
    TweenLite.from($('#popup h1'),0.5,{opacity:0, delay: speed});
  }

  $('.piece').each(function(){
    var distX = getRandomArbitrary(-250, 250),  
        distY = getRandomArbitrary(-250, 250),
        rotY  = getRandomArbitrary(-720, 720),
        rotX  = getRandomArbitrary(-720, 720),
        z = getRandomArbitrary(-500, 500);

    if(!from){
      TweenLite.to($(this), speed, {x:distX, y:distY, rotationX:rotX, rotationY:rotY, opacity: 0, z: z});   
    } else {
      TweenLite.from($(this), speed, {x:distX, y:distY, rotationX:rotX, rotationY:rotY, opacity: 0, z: z}); 
    }               
  });   
}

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}


$('.piece, h1').click(function(){
  breakGlass(); 
}); 
$('.reverse').click(function(){
  breakGlass('reverse');    
}); 

breakGlass(true);

I have changed CSS styles several times, without success.
I have also added some links to the libraries:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>

localStorage Value is Stored and Loaded Correctly but Not Applied to Checkbox Input

I am trying to use localStorage to store and load the checked state of a checkbox. The values are being correctly stored and retrieved from localStorage, but the checkbox is not reflecting these values when the page loads.

Here’s a summary of my code:

const driver = window.driver.js.driver;

const roleBasedSteps = {
    admin: {
        commonSteps: [
            {
                element: '#themeSwitchBtn',
                popover: {
                    title: 'Switch Theme',
                    description: `<p>Swtich between light and dark mode.</p>
                    <label><input type='checkbox' value='' class='startGuideOnLogin'> Always start guide on login</label>`,
                    position: 'auto'
                    // side: 'top', // left, top, right, bottom
                    // align: 'start' // start, center, end
                }
            },
            {
                element: '#navProfileBtn',
                popover: {
                    title: 'More Options',
                    description: 'More options to handle your profile.',
                    position: 'auto'
                }
            },
            {
                element: '#dashboardBtn',
                popover: {
                    title: 'Dashbaord',
                    description: 'Overview your overall progress in figures, charts and tables.',
                    position: 'auto'
                }
            },
            {
                element: '#emailBtn',
                popover: {
                    title: 'Email',
                    description: 'Email box where you can send, receive and read emails.',
                    position: 'auto'
                }
            },
            {
                element: '#usersDropdown',
                popover: {
                    title: 'Users List',
                    description: 'View all users list to manage them.',
                    position: 'auto'
                }
            }
        ],
        'index.php': [
            {
                element: '#adminDashboardCountStats',
                popover: {
                    title: 'Total Counts',
                    description: 'View all counts of meetings, clients, client interviews and placed clients.',
                    position: 'auto'
                }
            }
        ]
    },
    employee: {
        commonSteps: [
            {
                element: '#themeSwitchBtn',
                popover: {
                    title: 'Switch Theme',
                    description: 'Swtich between light and dark mode.',
                    position: 'auto'
                }
            },
            {
                element: '#navProfileBtn',
                popover: {
                    title: 'More Options',
                    description: 'More options to handle your profile.',
                    position: 'auto'
                }
            },
            {
                element: '#dashboardBtn',
                popover: {
                    title: 'Dashbaord',
                    description: 'Overview your overall progress in figures, charts and tables.',
                    position: 'auto'
                }
            },
            {
                element: '#emailBtn',
                popover: {
                    title: 'Email',
                    description: 'Email box where you can send, receive and read emails.',
                    position: 'auto'
                }
            },
            {
                element: '#usersDropdown',
                popover: {
                    title: 'Users List',
                    description: 'View all users list to manage them.',
                    position: 'auto'
                }
            }
        ],
        'index.php': [
            {
                element: '#employeeDashboardCountStats',
                popover: {
                    title: 'Total Counts',
                    description: 'View all counts of meetings, clients, client interviews and placed clients.',
                    position: 'auto'
                }
            }
        ]
    },
    candidate: {
        commonSteps: [
            {
                element: '#themeSwitchBtn',
                popover: {
                    title: 'Switch Theme',
                    description: 'Swtich between light and dark mode.',
                    position: 'auto'
                }
            },
            {
                element: '#navProfileBtn',
                popover: {
                    title: 'More Options',
                    description: 'More options to handle your profile.',
                    position: 'auto'
                }
            },
            {
                element: '#dashboardBtn',
                popover: {
                    title: 'Dashbaord',
                    description: 'Overview your overall progress in figures, charts and tables.',
                    position: 'auto'
                }
            },
            {
                element: '#emailBtn',
                popover: {
                    title: 'Email',
                    description: 'Email box where you can send, receive and read emails.',
                    position: 'auto'
                }
            },
            {
                element: '#jobsListBtn',
                popover: {
                    title: 'Jobs List',
                    description: 'View all listed jobs where you can check and give feedback to us.',
                    position: 'auto'
                }
            },
            {
                element: '#kanbanDropdown',
                popover: {
                    title: 'Interviews Board',
                    description: 'Mnanage your interviews and their progress.',
                    position: 'auto'
                }
            },
            {
                element: '#accountDropdown',
                popover: {
                    title: 'Account',
                    description: 'Manage your profile.',
                    position: 'auto'
                }
            },
            {
                element: '#calendarBtn',
                popover: {
                    title: 'Calendar',
                    description: 'View calendar and events.',
                    position: 'auto'
                }
            },
            {
                element: '#collapseBtn',
                popover: {
                    title: 'Collapse Sidebar',
                    description: 'Collapse sidebar menu.',
                    position: 'auto'
                }
            }
        ],
        'index.php': [
            {
                element: '#dashboardTotalCounts',
                popover: {
                    title: 'Total Counts',
                    description: 'View all counts of jobs, interviews and meetings.',
                    position: 'auto'
                }
            },
            {
                element: '#dashboardAppliedJobsCount',
                popover: {
                    title: 'Applied Jobs Graph',
                    description: 'View graphical representation below based on selected date range of applied jobs.',
                    position: 'auto'
                }
            },
            {
                element: '#dashboardInterviewsListTable',
                popover: {
                    title: 'Interviews List Table',
                    description: 'View tabular view of your interviews.',
                    position: 'auto'
                }
            }
        ],
        'email.php': [
            {
                element: '.composeEmailBtn',
                popover: {
                    title: 'Compose Email',
                    description: 'Opens compose emails section.',
                    position: 'auto'
                }
            },
            {
                element: '#emailSidebarSection',
                popover: {
                    title: 'Email Folders',
                    description: 'View emails in each folder.',
                    position: 'auto'
                }
            },
            {
                element: '#load-folder-emails',
                popover: {
                    title: 'Emails List',
                    description: 'View all emails of specific folder.',
                    position: 'auto'
                }
            }
        ],
        'jobs_list.php': [
            {
                element: '#jobsListPageSearch',
                popover: {
                    title: 'Search Job',
                    description: 'Search from jobs list.',
                    position: 'auto'
                }
            },
            {
                element: '#jobsListAction',
                popover: {
                    title: 'Give Rating',
                    description: 'Rate any job by clicking action button against the job.',
                    position: 'auto'
                }
            },
            {
                element: '#jobsListAction',
                popover: {
                    title: 'Give Review',
                    description: 'Review any job by clicking action button against the job.',
                    position: 'auto'
                }
            }
        ],
        'kanban.php': [
            {
                element: '#kanbanInterviews',
                popover: {
                    title: 'Pending Interviews',
                    description: 'Here is the list of all upcoming interviews.',
                    position: 'auto'
                }
            },
            {
                element: '#kanbanStage1',
                popover: {
                    title: 'First Stage',
                    description: 'Here is the list of interviews of first stage.',
                    position: 'auto'
                }
            },
            {
                element: '#kanbanStage2',
                popover: {
                    title: 'Second Stage',
                    description: 'Here is the list of interviews of second stage.',
                    position: 'auto'
                }
            },
            {
                element: '#kanbanRejected',
                popover: {
                    title: 'Rejected',
                    description: 'Here is the list of failed interviews.',
                    position: 'auto'
                }
            },
            {
                element: '#kanbanOffer',
                popover: {
                    title: 'Offer',
                    description: 'Here is the list of passed interviews.',
                    position: 'auto'
                }
            },
            {
                element: '.kanbanAddInterview1',
                popover: {
                    title: 'Add New',
                    description: 'Opens pop up to add new item.',
                    position: 'auto'
                }
            },
            {
                element: '.kanbanAddInterview2',
                popover: {
                    title: 'Add New',
                    description: 'Opens pop up to add new item.',
                    position: 'auto'
                }
            },
            {
                element: '.kanbanAddInterview3',
                popover: {
                    title: 'Add New',
                    description: 'Opens pop up to add new item.',
                    position: 'auto'
                }
            },
            {
                element: '.kanbanAddInterview4',
                popover: {
                    title: 'Add New',
                    description: 'Opens pop up to add new item.',
                    position: 'auto'
                }
            },
            {
                element: '.kanbanAddInterview5',
                popover: {
                    title: 'Add New',
                    description: 'Opens pop up to add new item.',
                    position: 'auto'
                }
            }
        ]
    }
};

function mergeGuideSteps(common, specific) {
    return [...common, ...specific];
}

const steps = mergeGuideSteps(roleBasedSteps[userRole].commonSteps, roleBasedSteps[userRole][currentPage]) || [];

function expandHiddenAreas(steps) {
    steps.forEach(step => {
        const element = document.querySelector(step.element);
        if (element) {
            let parent = element.parentElement;
            while (parent) {
                if (parent.style.display === 'none' || parent.style.visibility === 'hidden') {
                    parent.style.display = '';
                    parent.style.visibility = '';
                }
                if (parent.classList.contains('collapsed')) {
                    parent.classList.remove('collapsed');
                }
                parent = parent.parentElement;
            }
        }
    });
}

function isElementInCommonSteps(commonSteps, element) {
    const result = commonSteps.some(step => step.element === element);
    // console.log(`Checking if element ${element} is in common steps: ${result}`);
    return result;
}

function expandSidebarIfNeeded(commonSteps, currentElement) {
    const sidebar = document.querySelector('#navbarVerticalCollapse');
    const isMobileScreen = window.innerWidth <= 990;
    // console.log(window.innerWidth);

    const cElement = "#" + currentElement;

    if (isMobileScreen && isElementInCommonSteps(commonSteps, cElement)) {
        sidebar.classList.add('show');
    } else {
        sidebar.classList.remove('show');
    }
}

const driverObj = driver({
    showProgress: true,
    steps: steps,
    onHighlightStarted: (element) => {
        expandSidebarIfNeeded(roleBasedSteps[userRole].commonSteps, element.id);
    }
});

document.addEventListener('click', function (event) {
    if (event.target && event.target.classList.contains('startGuideOnLogin')) {
        const checked = '1';
        const unchecked = '0';

        if (event.target.value === '0' || event.target.value === '') {
            localStorage.setItem('startGuideOnLogin', checked);
            localStorage.setItem('startGuideBox', 'true');
            event.target.value = checked;
            event.target.checked = true;
        } else {
            localStorage.setItem('startGuideOnLogin', unchecked);
            localStorage.setItem('startGuideBox', 'false');
            event.target.value = unchecked;
            event.target.checked = false;
        }

        console.log('Checkbox value:', event.target.value);
    }
});

document.getElementById('startGuide').addEventListener('click', function () {
    expandHiddenAreas(steps);
    driverObj.drive();
});

window.addEventListener('load', function () {
    const isStartGuide = JSON.parse(localStorage.getItem('startGuideOnLogin'));
    const isBoxChecked = JSON.parse(localStorage.getItem('startGuideBox'));

    console.log('Start Guide: ' + isStartGuide);
    console.log('Input Box: ' + isBoxChecked);

    const checkbox = document.querySelectorAll('.startGuideOnLogin');

    if (checkbox) {
        checkbox.value = isStartGuide;
        checkbox.checked = isBoxChecked;
        
        console.log("values: " + checkbox.value + ", " + checkbox.checked);
    }

    if (isStartGuide === 1) {
        expandHiddenAreas(steps);
        driverObj.drive();
    }
});

Issue:

  1. The values are correctly stored in localStorage and can be seen when I inspect localStorage in the browser’s developer tools.
  2. However, when the page loads, the checkbox does not reflect the checked state based on the values stored in localStorage.

Troubleshooting Steps Taken:

  1. Verified the localStorage values using console.log.
  2. Checked the JavaScript console for errors.
  3. Ensured the checkbox has the correct class and is present in the DOM when the script runs.

Question:

What could be the reason why the checkbox state is not being applied despite localStorage values being correctly stored and loaded? How can I fix this issue?

Why do the moles in my Whack-a-Mole game never pop up? [closed]

I am trying to make a Whack-a-Mole game (codepen here) as part of a project on an online coding course. This is what the end result should look like, but in my code, the moles never pop up.

I only wrote the HTML and CSS — the JS was completely written by the instructors of the course.
Here is what I did in the HTML and CSS:

  • I used position: absolute for the images of the mole and the hill relative to their container.
  • Made a “visible” class and a “hidden” class for each mole.
  • The hidden class uses transition: margin-top 0.25s and overflow: hidden for the mole to hide.
  • Put the moles in a grid so they would be in 2 rows and 4 columns.
  • Assigned the hidden class to all the moles.

The course instructions say once you assign the hidden class to all the moles, the JS should start working, but it doesn’t.
When I try to run the code as it is, nothing happens. I’ve checked my code multiple times and even tried doing the project from scratch step by step, and I haven’t figured out what could be stopping the JS from doing its thing.

When I change the hidden class to the visible class and add this to the JS, it toggles the mole heads between those two classes, getting it to pop up and down. This is just to test out the transition, though.

window.addEventListener('DOMContentLoaded', () => {

  setInterval(() => {
    const moleHeads = document.querySelectorAll('.wgs__mole-head');
    for (let moleHead of moleHeads) {
      moleHead.classList.toggle('wgs__mole-head--hidden');
    }
  }, 1000);

});

Any help would be appreciated!

Issues with Event Handlers D3.js Update Function

I’m experiencing an issue where the mouseover event isn’t working after integrating the update function into my D3.js code. It seems the event listeners are not being recognized or triggered as expected. Could you help me troubleshoot this problem?

Thanks!

function onMouseOver(event, d){
    d3.select(this)
        .attr('class', 'tooltip')
        .transition()
        .duration(200);
    
    const g = d3.select(this.parentNode);

    g.append('text')
        .attr('class', 'val')
        .attr('x', () => x(d.event_name))
        .attr('y', () => y(d.total_event/2))
        .text(() => [d.total_event]);
};

function onMouseOut(d, i){
    d3.select(this).attr('class', 'bar');
    d3.select(this)
        .transition()   
        .duration(400)
    d3.selectAll('.val')
        .remove()
}


function update(dataBar) {

    x.domain(dataBar.map(d => d.event_name))
    xAxis.call(d3.axisBottom(x))
    .selectAll("text")
      .attr("class", "axis-label")
      .attr("transform", "rotate(-45)")
      .style("text-anchor", "end");

    
    y.domain([0, d3.max(dataBar, d => d.total_event)])
        .nice()
    yAxis.transition().duration(1000).call(d3.axisLeft(y).ticks(10));

    const u = svgBar.selectAll(".bar")
        .data(dataBar)

    u.enter().append("rect")
    .attr("class", "bar")
    .merge(u)
    .transition()
    .duration(1000)
        .attr("x", d => x(d.event_name))
        .attr("y", d => y(d.total_event))
        .attr("width", x.bandwidth())
        .attr("height", d => heightBar - y(d.total_event))
        .on("mouseover", onMouseOver)
        .on("mouseout", onMouseOut);


    u.exit().remove()
    
}

The mouseover event works fine without the update function. However, once I add the update function, the mouseover event stops working. I tried incorporating my onMouseOver and onMouseOut functions directly within the update function, but it didn’t resolve the issue. I also attempted to place the event handlers directly in the .on method, but that didn’t work either. My console shows an error indicating that mouseover is not recognized.

Thanks!

How unlink a function from the server [duplicate]

var polaroidGallery = function () {
var dataSize = {};
var dataLength = 0;
var currentData = null;
var xmlhttp = new XMLHttpRequest();

    function polaroidGallery(url) {
        observe();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var myArr = JSON.parse(xmlhttp.responseText);
                setGallery(myArr);
                init();
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

This feature works well on hosting. If you run it as part of a site on a local computer without a server, just in a browser, it does not work.
Which makes it bind only to http:// protocols.

Error:”Access to XMLHttpRequest at ‘file:///E:/Site/!PREVIEW/data/data.json’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge. data/data.json:1

It is clear here that data is not loaded.json . The file is in place, where it always is. And the hosting has the same relative paths.

How to change protocols to file:// for index.html ?

issue with connecting mongodb through mongoosejs

so I’m using this type of code to connect to mongodb – github link to code

const mongoose = require('mongoose')
cosnt s = "my connection url"
        mongoose.Promise = global.Promise
        mongoose.connection.on('connected', () => {
            this.logger.ready('[DB] DATABASE CONNECTED')
        })
        mongoose.connection.on('error', (err) => {
            this.logger.error(`Mongoose connection error: n ${err.stack}`)
        })
        mongoose.connection.on('disconnected', () => {
            this.logger.error('Mongoose disconnected')
        })

        await mongoose.connect(s, {
            connectTimeoutMS: 20000,
            maxIdleTimeMS: 20000,
            useUnifiedTopology: false
        })

error is below

MongooseServerSelectionError: connection timed out
    at Connection.openUri (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibconnection.js:825:32)
    at C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibindex.js:414:10
    at C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibhelperspromiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibhelperspromiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibindex.js:1288:10)
    at Mongoose.connect (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibindex.js:413:20)
    at Comfi.dbs (C:UsersmohitDocumentsMy_projectsComfiutilsComfi.js:425:18)
    at new Comfi (C:UsersmohitDocumentsMy_projectsComfiutilsComfi.js:63:8)
    at Object.<anonymous> (C:UsersmohitDocumentsMy_projectsComfiindex.js:16:13)
MongooseError: Operation `clients.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibdriversnode-mongodb-nativecollection.js:175:23)
    at listOnTimeout (node:internal/timers:581:17)
    at process.processTimers (node: internal/timers:519:7)

error on console without using process.on('unhandledRejection') event

node:events:498
      throw er; // Unhandled 'error' event
      ^

MongooseError: Operation `clients.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:UsersmohitDocumentsMy_projectsComfinode_modulesmongooselibdriversnode-mongodb-nativecollection.js:175:23)
    at listOnTimeout (node:internal/timers:581:17)
    at process.processTimers (node:internal/timers:519:7)
Emitted 'error' event on Comfi instance at:
    at emitUnhandledRejectionOrErr (node:events:403:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Node.js v22.5.0

so the thing is i have added my current ip or even allow anywhere but I’m still getting connection error.

one thing i noticed is that if i add an ip and then start the code, it will work but if i stop and start again then i get above errors. no i’m not adding my ip as temporary or one time and they are still active. image from mongodb section
i even tried to use my actual ip which i get from ipconfig /all under network section – ip4 but no luck

this code is used in my discord,js bot

Why JavaScript external classes doesn’t work? [closed]

I’m learning JavaScript

I reached Classes, and I don’t know why when i’m coding JS in external “.js” file and linking that to my HTML it doesn’t work but when i do this in html (internal), it works!

index.html

<div id="noticeContainer"></div>

app.js :

class Notice {
  constructor(message = 'Hello, World!') {
    this.element = document.createElement('div');
    this.element.textContent = message;
    this.css =
      'background: silver; border: 3px gray solid; color: gray; font: 18px sans-serif; padding: 8px; margin: 10px';
    this.element.style.cssText = this.css;
  }

  render(element) {
    if (element) {
      element.appendChild(this.element);
    } else {
      console.error('Error: element is null or undefined.');
    }
  }
}

class Success extends Notice {
  constructor(message = 'Success!') {
    super(message);
    this.element.style.background = 'palegreen';
    this.element.style.color = 'green';
    this.element.style.borderColor = 'green';
  }
}

class Info extends Notice {
  constructor(message = 'Information') {
    super(message);
    this.element.style.background = 'powderblue';
    this.element.style.color = 'blue';
    this.element.style.borderColor = 'blue';
  }
}

const noticeContainer = document.getElementById('noticeContainer');

const success = new Success();
success.render(noticeContainer);

const info = new Info();
info.render(noticeContainer);

I like to do this in external js 🙂

Will DynamoDB accept a string literal defined with backticks on separate lines as an UpdateExpression?

I have a lengthy UpdateExpression for my Dynamo update. I’m wondering if it’s possible to break it onto separate lines with string literal backticks and it still work?

Before:

UpdateExpression: "Set val1 = x, val2 = y, val3 = z" etc.

Can I break it out to something like

UpdateExpression: `
  Set val1 = x, 
  val2 = y, 
  val3 = z
`

I’m just afraid that all of the n will cause issues?

Styling Bootstrap 5 datalists

I’m aware that bootstrap datalists don’t have custom css support. And yes, I am aware that trying to comes with a few problem. That been said, I did it :), because I had a huge amount of options that was taking the entire web page and I needed to set a max height.

I found online a script (datalist-css) that let’s you apply custom css to datalists, however I am now trying to solve an issue that came with it. Click detection.

Whenever I open the datalist, it will only close if I select an option or if I click on another datalist.

Is there a way to detect when the datalist is unfoccused? If not, is there another way of applying a max height?

I am using mainly jquery btw. Here is a demonstration:

datalist not unfoccusing

Why is nesting level of a setTimeout should be greate than 5 to reduce minimal timeout to 4?

Good day to you.

It would be better to ask HTML5 spec devs, but virtue of my lack of intelligence I haven’t found any contacts yet.

So in details:
HTML 5 spec, 8.6 Timers says that “If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.”. And I have to ask why is exactly 5 and why we even have to reduce timeout to bigger than 4?

I am not able to type anything after execution for specific code

I want to run my nodemon file for that i have to type in the terminal but i am not able to do so. Here is the screen shot for the same.

enter image description here

So, In my other codes i can edit in terminal like cpp and c language but the codes include some server like or you can say webdev related codes it unable to write something so that’s a problem

Help me for the same so that i haven’t to restart the port again and again.