Tidio not installing in shopify when installed manually by adding script

I have added one js script before end of the body tag as tidio says in their documentation. But after adding that its not showing the chatbox. I follow as per they say in the doc here https://help.tidio.com/hc/en-us/articles/5379640857884-Install-Tidio-on-Shopify#:~:text=You%20will%20make%20the%20Tidio,Widget%20and%20save%20the%20changes.

Let me know if there is any other way in shopify to import modules from url

enter image description here

Remove the topmost key of an object?

Is it possible to flatten or remove the topmost key of an object? For example:

const obj = {
  page: {
    title: 'x',
    images: {
      0: {
        src: '...'
      }
    }
  }
}

So I can get:

{
  title: 'x',
  images: {
    0: {
      src: '...'
    }
  }
}

I tried with map but the result isn’t what I am looking for:

const x = Object.keys(obj).map((key)=>{
  return obj[key]
})

Any ideas?

Horizontal Scrollbar using JavaScript

In the image shown above, I want to implement that horizontal Scrollbar.
The object object have stored in a js object

Can anyone help me to implement that scroll bar.

Thanks in advance

I know how to implement scroll bar using html but using html the element is display in div which will may not display the subitems of the category.

Firefox blocks one tab from opening, but not another

I’ve got an library, which provides methods for opening pop-up tabs (they interact with my app via window.postMessage api).

In first case, I’ve got Login button that triggers login service immediately:

loginButton.addEventListener(() => {
    myService.openLogin(); // everything works perfectly fine, new tab is opened
})

In second case, I’ve got a payment button, which delegates opening payment window after doing some checks

paymentButton.addEventListener(() => {
   dispatch({type: "todo"})
})

const myReducer = ... = {
   onTodo() {
      //perform a lot of checks
      myService.openPayment();
   }
}

What I described above is nutshell, in reality it takes a lot of functions and code, but in the end it calls service method. The time between click and openPayment() triggered is about 300ms.
I’ve heard that there’s some kind of “click context” that is different in second case, so Firefox believes that my service is spam and blocks it.

Unfortunately I can’t reproduce it and just hope someone have encountered such a problem

How to highlight blockquote text if word There was inside the array using JavaScript

When the words in the array are equal to the noun word blockquote
If the word is not equal or does not exist in the array “rebaz”, do not highlight it
const rebaz = ["something", "Hello", "BMW"];
That’s just an example, css
I want to javascript

.highlight {
  color:white;
  background:black;
  line-height: 150%;
}
<blockquote><span class="highlight">
 Hello testing something Hello testing something Hello testing something Hello testing something Hello testing something Hello testing something Hello testing something  
</span></blockquote>

Problem with JavaScript not dynamically updating the options

I’m writing a simple frontend to help players create a tournament. But for some reason the options are not showing up in the second round.

Recreate problem:

  • choose a map
  • choose # of players
  • choose teams
  • click add another round

You’ll see the option for # of players is not showing in round 2

Can anyone help me find the issue?

This is the codepen link – https://codepen.io/Nim-Chimpsky/pen/NWoOQxZ

Thanks.

document.addEventListener('DOMContentLoaded', function() {
    // Initialize the counter for the number of rounds.
    let roundCount = 1;
    const roundsContainer = document.querySelector('.rounds-container');
    // Select the first round element to use as a template for additional rounds.
    const firstRound = document.querySelector('.round');

    // Function to update the team options based on the selected number of players.
    function updateTeamsOptions(selectedPlayers, roundContainer) {
        // Define the possible team configurations.
        const teamSizes = {
            'Singles': 1,
            'Doubles': 2,
            'Triples': 3,
            'Quads': 4,
            'Fivers': 5,
            'Sixers': 6,
            'Crusades': 12
        };

        // Enable or disable team options based on the selected number of players.
        roundContainer.querySelectorAll('.team-option').forEach(option => {
            const teamSize = teamSizes[option.getAttribute('data-value')];
            if (selectedPlayers % teamSize === 0 && selectedPlayers / teamSize >= 2) {
                option.disabled = false;
            } else {
                option.disabled = true;
                option.classList.remove('selected');
            }
        });
    }

    // Function to update the player options based on the selected map.
    function updatePlayersOptions(mapValue, roundContainer) {
        // Initialize the HTML content for player options.
        let playerOptions = '';
        // Determine the maximum number of players based on the map selection.
        const maxPlayers = mapValue === 'Other' ? 24 : 12;

        // Generate buttons for selecting the number of players.
        for (let i = 2; i <= maxPlayers; i++) {
            playerOptions += `<button class="player-option" data-value="${i}">${i}</button>`;
        }

        // Update the players container with the generated buttons.
        const playersContainer = roundContainer.querySelector('#players');
        if (playersContainer) {
            playersContainer.innerHTML = playerOptions;
        }

        // Add click event listeners to the newly created player option buttons.
        roundContainer.querySelectorAll('.player-option').forEach(option => {
            option.addEventListener('click', function() {
                clearSelected(roundContainer.querySelectorAll('.player-option'));
                this.classList.add('selected');
                updateTeamsOptions(parseInt(this.getAttribute('data-value')), roundContainer);
            });
        });
    }

    // Function to clear the 'selected' class from a collection of buttons.
    function clearSelected(buttons) {
        buttons.forEach(btn => btn.classList.remove('selected'));
    }

    // Function to initialize event listeners for map and team option buttons.
    function initializeEventListeners(roundElement) {
        // Add click event listeners to map option buttons.
        roundElement.querySelectorAll('.map-option').forEach(option => {
            option.addEventListener('click', function() {
                const roundContainer = this.closest('.round');
                clearSelected(roundContainer.querySelectorAll('.map-option'));
                this.classList.add('selected');
                updatePlayersOptions(this.getAttribute('data-value'), roundContainer);
            });
        });

        // Add click event listeners to team option buttons.
        roundElement.querySelectorAll('.team-option').forEach(option => {
            option.addEventListener('click', function() {
                if (!this.disabled) {
                    const roundContainer = this.closest('.round');
                    clearSelected(roundContainer.querySelectorAll('.team-option'));
                    this.classList.add('selected');
                }
            });
        });
    }

    // Function to create and append a new round configuration.
    function createRound() {
        // Increment the round counter.
        roundCount++;
        // Clone the first round element to use as a template for the new round.
        const roundTemplate = firstRound.cloneNode(true);

        // Update the round number in the template.
        roundTemplate.querySelector('h2').textContent = `Round ${roundCount}`;
        // Clear the players container in the template.
        roundTemplate.querySelector('#players').innerHTML = '';
        // Update the ID of the players container to be unique.
        roundTemplate.querySelector('#players').id = `players${roundCount}`;
        // Reset the selection of buttons in the template.
        roundTemplate.querySelectorAll('button').forEach(button => {
            button.classList.remove('selected');
            if (button.classList.contains('team-option')) {
                button.disabled = true;
            }
        });

        // Reset map options and set 'Other' as the default selected map.
        const mapOptions = roundTemplate.querySelectorAll('.map-option');
        mapOptions.forEach(btn => btn.classList.remove('selected'));
        const defaultMapButton = roundTemplate.querySelector(`.map-option[data-value="Other"]`);
        if (defaultMapButton) {
            defaultMapButton.classList.add('selected');
            updatePlayersOptions('Other', roundTemplate);
        }

        // Create and add a delete button for the new round.
        const deleteButton = document.createElement('button');
        deleteButton.textContent = `Delete Round ${roundCount}`;
        deleteButton.addEventListener('click', function() {
            // Remove the round element from the container when the delete button is clicked.
            roundsContainer.removeChild(this.parentElement);
            // Decrement the round counter.
            roundCount--;
        });
        roundTemplate.appendChild(deleteButton);

        // Initialize event listeners for the new round.
        initializeEventListeners(roundTemplate);

        // Append the new round to the rounds container.
        roundsContainer.appendChild(roundTemplate);
    }

    // Add a click event listener to the "Add Another Round" button.
    const addRoundButton = document.getElementById('addRound2');
    addRoundButton.addEventListener('click', createRound);

    // Initialize the first round with default settings and event listeners.
    initializeEventListeners(firstRound);
    updatePlayersOptions('Other', firstRound);
});
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container {
    display: flex;
    justify-content: space-between;
    padding: 20px;
}

.left-side, .right-side {
    flex: 1;
    padding: 20px;
}

.rounds-container {
    margin-bottom: 20px;
}

.options {
    margin-bottom: 20px;
}

.options label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

button {
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button:hover {
    background-color: #e0e0e0;
}

.selected {
    background-color: #4CAF50; /* Green background for selected buttons */
    color: white;
}

h2 {
    color: #333;
    margin-bottom: 20px;
}

#addRound2 {
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    font-size: 1em;
}

#addRound2:hover {
    background-color: #45a049;
}

.right-side label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

#numWinners {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Rounds Configuration</title>
    <link rel="stylesheet" href="style.css"> <!-- Link to your CSS file -->
</head>
<body>
    <div class="container">
        <div class="left-side">
            <div class="rounds-container">
                <div class="round">
                    <h2>Round 1</h2>
                    <div class="options">
                        <label>Map:</label>
                        <button class="map-option" data-value="12D">12D</button>
                        <button class="map-option" data-value="LandRush">Land Rush</button>
                        <button class="map-option selected" data-value="Other">Other</button>
                    </div>

                    <div class="options">
                        <label>Players:</label>
                        <div id="players"></div>
                    </div>

                    <div class="options">
                        <label>Teams:</label>
                        <button class="team-option" data-value="Singles">Singles</button>
                        <button class="team-option" data-value="Doubles">Doubles</button>
                        <button class="team-option" data-value="Triples">Triples</button>
                        <button class="team-option" data-value="Quads">Quads</button>
                        <button class="team-option" data-value="Fivers">Fivers</button>
                        <button class="team-option" data-value="Sixers">Sixers</button>
                        <button class="team-option" data-value="Crusades">Crusades</button>
                    </div>
                </div>
            </div>
            <button id="addRound2">Add Another Round</button>
        </div>
        <div class="right-side">
            <label>Number of Winners:</label>
            <div id="numWinners"></div>
        </div>
    </div>
    <script src="script.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>

How to ask for screen recording permission in electron app in Mac OS?

I am trying to create an app and ask for screen recording permission, but the app asks for permission if i directly execute desktopcapturer.getsources() function with the correct app name added.

Here is an example,

const sources = await desktopCapturer.getSources({
      types: ["screen"],
      thumbnailSize: { width: 1920, height: 1080 },
});

I also tried to use below but it was not adding my application name in the system preferences screen recording permissions window,

const permissionStatus: string =
      systemPreferences.getMediaAccessStatus("screen");

    // throwing error if no permission given
    if (permissionStatus !== "granted") {
      // Open Screen privacy settings in System Preferences
      shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture');
    
      // throw new Error("screen capture, access denied");
      console.log("Permission status ", permissionStatus);
    }

I want my app to show the following window when i start it or when my app does not have required permissions
Visual Studio Code asking screen recording permission in mac

But my app currently just opens the permission window without the name of my app added there as shown below,

screen recording permission screen without app name

How can generate input values n+1 according a main input value? [closed]

How can create a script to auto assign input values according a class?

I’m trying to auto assign values like n + 1 according an input master

For example the input master has value = 4 and child inputs should have input values 1,2,3,4

Master 1 INPUT <input type="text" value="4">

<ul>
  <li>1 Input<input name="demo" type="text" value="1"></li>
  <li>2 Input<input name="dog" type="text" value="2"></li>
  <li>3 Input<input name="vegetables" type="text" value="3"></li>
  <li>4 Input<input name="green"type="text" value="4"></li>
</ul>

NOTE: I don’t need to add more child inputs, those should only show first values

Master 3 INPUT <input type="text" value="3">

<ul>
  <li>1 Input<input name="demo2" type="text" value="1"></li>
  <li>2 Input<input name="dog2"  type="text" value="2"></li>
</ul>

Here is the demo

enter image description here

Trouble with TypeScript error related to missing property on object

I have a STEPS_CONFIG object that defines various steps, each with a set of properties including defaultValues. However, when I try to access defaultValues from the currentStep object, TypeScript throws an error indicating that the property does not exist on the type.

Here’s a version of the relevant code:

export const STEPS = {
  init: 'init',
  profile_picture: 'profile_picture',
  driving_license_front: 'driving_license_front',
  driving_license_back: 'driving_license_back',
  vehicle_card_front: 'vehicle_card_front',
  vehicle_card_back: 'vehicle_card_back',
  vehicle_insurance: 'vehicle_insurance',
  verification_photo: 'verification_photo',
  applicant_contract: 'applicant_contract',
} as const;

export const STEPS_CONFIG = () => ({
  [STEPS.init]: {
    title: `${t('enterBasicInformation')}`,
    renderForm: <Init />,
    // TODO: Remove unused properties from the init step and fix possible errors
    properties: {
      boxTitle: 'Box Title',
      rulesList: ['rule1', 'rule2', 'rule3'],
      image: 'aedfsdafsdf',
      selfieMode: false,
      enabled: false,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        vehicle_type: 'cab' as const,
        referral_code: toEnNumbers(data.referralCode),
        national_code: toEnNumbers(data.nationalCode)!,
        activity_location: data.activityLocation.id as number,
        father_name: data.fatherName as string,
      };
      const response = await init(formattedData);
      if (response.ok) {
        useWizardStore
          .getState()
          .addRemainingSteps(response.body.remaining_steps);
      }
      return response;
    },
    defaultValues: {
      vehicleType: 'سواری',
      haveReferralCode: false,
      activityLocation: null,
      fatherName: '',
      nationalCode: '',
    },
  },
  [STEPS.profile_picture]: {
    title: `${t('uploadProfilePicture')}`,
    description: `${t('takeSelfieRule')}`,
    properties: {
      boxTitle: `${t('userSelfie')}`,
      rulesList: [
        `${t('fullViewImageRule')}`,
        `${t('profilePictureExtraRules')}`,
      ],
      image: getFileURL('images/rules/profile-picture.svg'),
      correctionImage: useWizardStore.getState().remainingSteps.profile_picture,
      selfieMode: true,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.profile_picture,
        image: data.image,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
  },
  [STEPS.driving_license_front]: {
    title: `${t('uploadDrivingLicenseFront')}`,
    description: `${t('takeDrivingLicnseRuleFront')}`,
    renderForm: <DrivingLicenseFront />,
    properties: {
      boxTitle: `${t('drivingLicenseFrontImage')}`,
      rulesList: [`${t('originalDocumentRules')}`, `${t('overEighteenRules')}`],
      image: getFileURL('images/rules/driving-license-front.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.driving_license_front,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.driving_license_front,
        image: data.image,
        first_name: data.firstName,
        last_name: data.lastName,
        birth_date: toEnNumbers(data.birthDate)!,
        gender: data.gender.value,
        license_issuance_date: toEnNumbers(data.licenseIssuanceDate)!,
        license_valid_for: data.drivingLicenseValidityPeriod.value,
        license_type: data.drivingLicenseType.value,
        license_number: toEnNumbers(data.drivinglicenseNumber)!,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
  },
  [STEPS.driving_license_back]: {
    title: `${t('uploadDrivingLicenseBack')}`,
    description: `${t('takeDrivingLicnseRuleBack')}`,
    properties: {
      boxTitle: `${t('drivingLicenseBackImage')}`,
      rulesList: [
        `${t('originalDocumentRules')}`,
        `${t('readableDrivingLicenseBack')}`,
      ],
      image: getFileURL('images/rules/driving-license-back.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.driving_license_back,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.driving_license_back,
        image: data.image,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
  },
  [STEPS.vehicle_card_front]: {
    title: `${t('uploadVehicleCardFront')}`,
    description: `${t('takeVehicleCardFrontRule')}`,
    renderForm: <VehicleCardFront />,
    properties: {
      boxTitle: `${t('vehicleCardFrontImage')}`,
      rulesList: [
        `${t('originalDocumentRules')}`,
        `${t('clearDocumentRules')}`,
        `${t('exactCarRules')}`,
      ],
      image: getFileURL('images/rules/vehicle-card-front.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.vehicle_card_front,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.vehicle_card_front,
        image: data.image,
        ...(data.plate.part_a && { plate_part_a: data.plate.part_a }),
        ...(data.plate.part_b && { plate_part_b: data.plate.part_b }),
        ...(data.plate.iran_id && { plate_iran_id: data.plate.iran_id }),
        ...(data.plate.character && { plate_character: data.plate.character }),
        plate_type: data.plate.type,
        vin: data.vin,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
    defaultValues: {
      plate: {
        type: 1,
        part_a: null,
        part_b: null,
        character: null,
        iran_id: null,
      },
      vin: '',
    },
  },
  [STEPS.vehicle_card_back]: {
    title: `${t('uploadVehicleCardBack')}`,
    description: `${t('takeVehicleCardBackRule')}`,
    renderForm: <VehicleCardBack />,
    properties: {
      boxTitle: `${t('vehicleCardBackImage')}`,
      rulesList: [
        `${t('originalDocumentRules')}`,
        `${t('clearDocumentRules')}`,
        `${t('exactCarRules')}`,
      ],
      image: getFileURL('images/rules/vehicle-card-back.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.vehicle_card_back,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.vehicle_card_back,
        image: data.image,
        vehicle_model_id: data.vehicleModel.id,
        vehicle_color_id: data.vehicleColor.id,
        fuel_type: data.fuelType.value,
        vehicle_production_year: toEnNumbers(data.productionYear)!,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
    defaultValues: {
      vehicleColor: null,
      vehicleModel: null,
      productionYear: '',
    },
  },
  [STEPS.vehicle_insurance]: {
    title: `${t('uploadVehicleInsurance')}`,
    description: `${t('takeVehicleInsuranceRule')}`,
    renderForm: <VehicleInsurance />,
    properties: {
      boxTitle: `${t('vehicleInsuranceImage')}`,
      rulesList: [
        `${t('originalDocumentRules')}`,
        `${t('fillInsuranceCodeRules')}`,
        `${t('insuranceCodeDigitsRules')}`,
        `${t('onlyInsuranceCodeRules')}`,
        `${t('theNewestVehicleInsuranceRules')}`,
      ],
      image: getFileURL('images/rules/vehicle-insurance.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.vehicle_insurance,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.vehicle_insurance,
        image: data.image,
        insurance_id: toEnNumbers(data.insuranceNumber)!,
        insurer_national_code: toEnNumbers(data.insurerNationalCode)!,
        insurance_expiration_date: toEnNumbers(data.insuranceExpirationDate)!,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
    defaultValues: {
      hasInsuranceNumber: false,
    },
  },
  [STEPS.verification_photo]: {
    title: `${t('verificationPhoto')}`,
    description: `${t('takeVerificationPhotoRule')}`,
    properties: {
      boxTitle: `${t('verificationImage')}`,
      rulesList: [`${t('keepLicenseRules')}`],
      image: getFileURL('images/rules/verification-photo.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.verification_photo,
      selfieMode: true,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.verification_photo,
        image: data.image,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
  },
  [STEPS.applicant_contract]: {
    title: `${t('takeSignatureTitle')}`,
    renderForm: <ApplicantContract />,
    properties: {
      boxTitle: `${t('takeSignatureTitle')}`,
      rulesList: [
        `${t('uploadContractRules')}`,
        `${t('confirmContractRules')}`,
      ],
      image: getFileURL('images/rules/applicant-signature.svg'),
      correctionImage:
        useWizardStore.getState().remainingSteps.applicant_contract,
      selfieMode: false,
      enabled: true,
    },
    onSubmit: async (data: any) => {
      const formattedData = {
        kind: STEPS.applicant_contract,
        image: data.image,
        training_place_id: data.trainingPlace.id,
      };
      const response = await uploadDocument(formattedData);
      return response;
    },
  },
});


 const currentStep =
    STEPS_CONFIG()[stepLabels[activeStep] as keyof typeof STEPS];

const methods = useForm({
    mode: 'all',
    defaultValues: currentStep.defaultValues,
  });

and in this line

defaultValues: currentStep.defaultValues,

I got this error

Property 'defaultValues' does not exist on type '{ title: string; description: string; properties: { boxTitle: string; rulesList: string[]; image: string; correctionImage: { image_url: string; message: string; } | undefined; selfieMode: boolean; enabled: boolean; }; onSubmit: (data: any) => Promise<any>; }'.

Include Javascript Deobfuscation inside a seperate function?

My website at the moment displays a captcha. After the captcha is completed I need to use The javascript I have posted below to deobfuscate my code and replace the content’s of the page using the deobfuscated code. I need help getting the deobfuscated website code to display once the captcha is completed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Page</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        #content {
            display: none;
            text-align: center;
        }
    </style>
</head>

<body>
    <?php
    include 'verify_recaptcha.php';

    ?>

    <div id="content">
        
        <h1>Welcome</h1>
       
    </div>
    <div id="recaptcha-container"></div>
    
    <script>
        function onLoadCallback() {
            grecaptcha.render('recaptcha-container', {
                'sitekey': 'SITEKEY',
                'callback': onCaptchaCompleted
            });
        }

        function onCaptchaCompleted(response) {
            document.getElementById('content').style.display = 'block';
        }

        window.onload = onLoadCallback;
    </script>
    
</body>
</html>

<script language="JavaScript" type="text/javascript">
<!--
  function normalize(obtext){var ot = obtext; var ra = ["+","-","&","*","!","@","#","$","%","^","(",")","~",",",".","<",">","/","?"]; for(var i=0;i<ra.length;i++) while(ot.indexOf(ra[i]) > -1) ot = ot.replace(ra[i],""); var tcrb = "", enca = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(var i_var = 0; i_var < ot.length; i_var += 2) { var val = 0xFF - (((enca.indexOf(ot.substr(i_var,1))*36+enca.indexOf(ot.substr(i_var+1,1)))) >> 2); var res = ""; while(val >= 0x10) { res = enca.charAt(val % 0x10) + res; val = parseInt(val / 0x10); }; if(val > 0) res = enca.charAt(val)+res; while (res.length < 2) res = "0"+res; tcrb+=unescape("%"+res); }return tcrb;}
 document.write(normalize("OBFUSCATED CODE));
 document.write(normalize("OBFUSCATED CODE));
-->
</script>

how to open custom context menu when the user right-clicks on specific words? JavaScript

how to open custom context menu to open when the user right-clicks on specific words? JavaScript

I’ve been looking for that for a long time how can I For a word that has textarea the custom context menu opened the word should be specific have in the array to recognize him Can anyone help me. That’s just an example of a context menu, not in a textarea like this https://codepen.io/rebaz-xoshnaw-the-builder/pen/XWOPvRe if textarea value not have specificwords word It shouldn’t be open The code I put as a suggestion for my request has nothing to do with the source

var specificwords = [‘hi’, ‘hello’, ‘yo’, ‘hey’, ‘some’, ‘howdy’];

document.querySelector('textarea').addEventListener('contextmenu', function (e) {
        e.preventDefault();

        var startPosition = this.selectionStart,
            endPosition = this.selectionEnd;

        while (this.value.charAt(startPosition) !== ' ' && startPosition >= 0) {
            startPosition--;
        }

        while (this.value.charAt(endPosition) !== ' ' && endPosition < this.value.length) {
            endPosition++;
        }

        this.selectionStart = startPosition + 1;
        this.selectionEnd = endPosition;
})
 
   <textarea>hello This is some text. Click on any word and then do right click</textarea>

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘user’)

While registering a user I am getting this error.
Apparently I must be forwarded to the login page after registering the user but I am getting this error. Looks like the problem is with fetching the user. Can anyone help me out in this?

Here is my different codes

authAction.js

export const userRegister = createAsyncThunk(
  "auth/register",
  async (
    {
      name,
      role,
      email,
      password,
      phone,
      organisationName,
      address,
      hospitalName,
      website,
    },
    { rejectWithValue }
  ) => {
    try {
      const response = await fetch("http://localhost:8080/api/v1/auth/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name,
          role,
          email,
          password,
          phone,
          organisationName,
          address,
          hospitalName,
          website,
        }),
      });

      const data = await response.json();

      if (data?.success) {
        alert("User Registered Successfully");
        window.location.replace("/login");
      }
    } catch (error) {
      console.error(error);
      if (error.message) {
        return rejectWithValue(error.message);
      } else {
        return rejectWithValue("An error occurred during registration");
      }
    }
  }
);

authSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { getCurrentUser, userLogin, userRegister } from "./authActions";

const token = localStorage.getItem("token")
  ? localStorage.getItem("token")
  : null;

const initialState = {
  loading: false,
  user: null,
  token,
  error: null,
};
const authSlice = createSlice({
  name: "auth",
  initialState: initialState,
  reducers: {},
  extraReducers: (builder) => {
// REGISTER user
    builder.addCase(userRegister.pending, (state) => {
      state.loading = true;
      state.error = null;
    });
    builder.addCase(userRegister.fulfilled, (state, { payload }) => {
      state.loading = false;
      state.user = payload.user;
    });
    builder.addCase(userRegister.rejected, (state, { payload }) => {
      state.loading = false;
      state.error = payload;
    });
},
});

export default authSlice;

authSerivce.js

import { userLogin, userRegister } from "../redux/features/auth/authActions";
import store from "../redux/store";
export const handleRegister = (
  e,
  name,
  role,
  email,
  password,
  phone,
  organisationName,
  address,
  hospitalName,
  website
) => {
  e.preventDefault();
  try {
    store.dispatch(
      userRegister({
        name,
        role,
        email,
        password,
        phone,
        organisationName,
        address,
        hospitalName,
        website,
      })
    );
  } catch (error) {
    console.log(error);
  }
};

store.js

import {configureStore} from '@reduxjs/toolkit'
import authSlice from './features/auth/authSlice';

const store = configureStore({
    reducer:{
        auth: authSlice.reducer,
    }
})

export default store;

How to set dark mode to turn on automatically based on time?

How to set dark mode to turn on automatically based on time?

code html

<div id="theme-toggler" class="fas fa-moon "></div>

css

body.active {
    --backgound: #f6f6f6;
    --backgound-overlay: rgba(255, 255, 255, 0.4);
    --font-colour: #202020
}

:root {
    --backgound: #202020;
    --backgound-overlay: rgba(32, 32, 32, 0.8);
    --font-colour: #ecbf1d
}
html {
    background: var(--backgound);
}

body {
    box-sizing: border-box;
    width: 100%;
    margin: 0;
    padding: 0;
}

js

let themeToggler = document.getElementById('theme-toggler');

themeToggler.onclick = () => {
  themeToggler.classList.toggle('fa-sun');

  if (themeToggler.classList.contains('fa-sun')) {
    document.body.classList.add('active');
  } else {
    document.body.classList.remove('active');
  }
};

How to set dark mode to turn on automatically based on time?

NEXTJS : Target Element in the middle of the screen

I am currently using nextjs for a project. I got some problems.

When I use it makes an element positioned at the top of the screen. However, there is a floating Navbar from app/layout.tsx blocking its visibility. So I want move the target element down to the center when clicked on instead if possible.

How do I achieve this?

Thank you in advance.

I’m currently trying scrollIntoView but still experimenting on them. No result at the time I’m writing.