Cannot declare the “else” statement in Java script Visual Studio Code?

New to coding and getting errors in basic coding. Following a youtube tutorial for learning but getting the error even after coding the same way as shown in my tutorial video.

var age = prompt ("what is ur age?");

`If ( (age>= 18)   &&   (age<= 35) ); {

var status = “my audience”;
console.log (status);} else {
var status = “not intrested”;
console.log(status);
}`

Upon running the program, the error generated is Unexpected token ‘else’.

Manifest v3 inject script from popup.js

In manifest v2 this code worked and injected the script when button was clicked:

popup.js v2 (works)

document.addEventListener('DOMContentLoaded', function () {
// Get Scan button by ID
var scanButton = document.getElementById('btnScan');

// Define Scan button on click action
scanButton.onclick = function () {
    chrome.tabs.executeScript(null, {
        file: 'Scripts/script.js'
    });
    window.close();
    }
});

Now in manifest v3, chrome.tabs.executeScript is replaced with chrome.scripting.executeScript.

scripting permission is added in manifest.json.

popup.js v3 ()

document.addEventListener('DOMContentLoaded', function () {
// Get Scan button by ID
var scanButton = document.getElementById('btnScan');

// Define Scan button on click action
scanButton.onclick = function () {
    chrome.scripting.executeScript
        (
        {
            target: { tabId: null}, // ???????
            files: ['Scripts/script.js']
        }
        );
    window.close();
    }
});

The problem is that chrome.tabs.executeScript requires tabId value as one of the parameters.
How can I get tabId value in popup.js or convert the manifest v2 version javascript so that it works the same?

Hide two blocks at the same time

I have a method on a page that opens and hides a scrolling block in certain places

<!DOCTYPE html>
<html lang="en">

<head>
  <script>
    var sideMenu, footer, wrapper, nsl;

    document.addEventListener("DOMContentLoaded", init, false);

    function check() {
      var range = document.body.scrollHeight - footer.offsetHeight;
      var position = (nsl.offsetHeight + nsl.getBoundingClientRect().y - wrapper.getBoundingClientRect().y).toFixed(1);

      nsl.innerText =
        'n Range: ' + range +
        'n Position: ' + position;

      if (window.scrollY > 200 && (range > position)) {
        nsl.style.visibility = "visible";
      } else {
        nsl.style.visibility = "hidden";
      }
    };

    function init() {
      sideMenu = document.getElementById('sideMenu');
      footer = document.getElementById('footer');
      wrapper = document.getElementById('wrapper');
      nsl = document.getElementById('navShareLink');

      window.onscroll = check;
      check();
    }
  </script>
  <style>
    .article-wrapper {
      min-height: 200vh;
      position: relative;
      top: 0;
      left: 0;
    }

    .article-wrapper p:first-of-type {
      margin-top: 0;
    }

    footer {
      min-height: 100vh;
      background-color: lightskyblue;
    }

    .sidemenu-shares {
      z-index: 999;
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      justify-content: center;
      position: fixed;
      top: 0;
      right: 0;
      flex-wrap: nowrap;
      gap: 40px;
    }

    .rectangle {
      z-index: 998;
      transition: opacity 0.5s;
      padding: 5px;
      height: 106px;
      width: 123px;
      background-color: rgba(200, 0, 0, 0.1);
      border-radius: 24px;
    }

    .content {
      height: 50px;
      border: 1px dotted gray;
    }

  </style>
</head>

<body>
  <div id="wrapper" class="article-wrapper">

    <div id='sideMenu' class="sidemenu-shares">
      <div id="navShareLink" class="rectangle">

      </div>
    </div>

    <div class="main-banner">
      <h1>Title</h1>
    </div>

    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
  </div>

  <footer id='footer'>
    Footer...
  </footer>
</body>

</html>

Now it turns out that in my sideMenu there is only one block, but I want to add another one and so that they hide and open together

This is how the code should look like after adding the block

<div id='sideMenu' class="sidemenu-shares">
    <div id="navShareLink" class="rectangle">

    </div>

    <div id="navToTop" class="to-top">

    </div>
</div>

But now I can’t make them both hide

I am trying to do the following in js

nsl = document.querySelectorAll("#navShareLink, #navToTop");

But everything works incorrectly and nothing is hiding at all

Get cookie value by name and change style DOM element

Get cookie value by name and change style DOM element. I want to get the Arabic language from cookie and change the style of div to “dir=rtl” but I don’t know I can do this in one function

   <h2 class="text">{% translate 'Admin' %}</h2>
       <form class="login-form" method="post">
             {% csrf_token %}
            <div class="login-form">
                  {% include 'form_login.html' with field=form.username %}
             </div>             
        </form>
</div>
<style>
Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});                                                                         ```                                                                                           there I want to get language and if this is Arabic do change of class="login-form" to style dir="rtl"                                                                              ```
    }
});
</style>

Please how I can do this

assign variable to value of Dictionary Javascript

I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.

main.js

import myDictionary from "myDictionary.js"

const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)


myDictionary.js

const myDictionary = {
key: variables.item
}

so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.

as always any help is greatly appreciated

how to use regex in my e2e javascript cypress test

How should I use regex here so I can catch only hana input, not the user name hanna111? the way I used it is not working

it('creates and saves user ', () => {
    const user = 'hana111';
    createUser(user);
    cy.visit(`/security/user/${user}`);
    cy.get('input[name="myuser"]').type('hana');
    cy.contains('button', 'Save').click();
    cy.visit('/security/users');
    cy.get('table').contains('td', /<hana$/).should('exist');
});

How to rerender useEffect when state change

Need to update the useEffect call when I update the state. can anyone correct the code?
Currently is working like this screenshot the updated data is rendering after pre-render data.
what is needed is when I click on any filter every it renders new data.
Check screenshot

Here is my code :

const PAGE_NUMBER =1;

export const SimpleInfiniteList = () => {

  const [img, setImg] = useState('')
  const [page, setPage] = useState(PAGE_NUMBER)
  const iddata = img.slice(-1)
  const [filter, setFilter] = useState('top')
  const [, forceUpdate] = useReducer(x => x + 1, 0);


useEffect(() => {
  const filt = () => {

    if(filter > 0){
      filt()
      
    }

  }

}, [])
  

 

  useEffect( () => {
    forceUpdate()
   
  fetch(`https://www.reddit.com/r/ProgrammerHumor/${filter}.json?after=${ iddata.length > 0 ? iddata.map(id => `t3_${id.data.id}`): ''}&page=${page}&limit=2`)
  .then(response => response.json())
  .then(data => setImg([...img, ...data.data.children], 
    )
  )
}, [filter,page])



console.log(img)



const scrollToEnd = () => {
  setPage(page + 1) 
}
window.onscroll = function () {
  const bottom =  Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
  
  if (bottom,
     Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
    ) {
      scrollToEnd() 
      console.log('loading....')
  }
}
}

Can I insert triple backticks inside of single backticks?

So I want the default value to rendered on the first render, but I can not find the way how I can insert triple backticks into single backticks so far.

My last attempt was adding it in defaultValue variable and inserting it this way.

function App() {
  let defaultValue = ```
  function hey() {
    return "hello";
  }
  ```
  const [inputValue, setInputValue] =
    useState(`
  # this is a header
  ## This is a sub-heading...
  ### And here's some other cool stuff:
  ${defaultValue}
  `);

  return (
    <div className="wrapper">
      <div className="editContainer">
        <div className="toolbar">Editor</div>
        <textarea
          id="editor"
          onChange={(e) => {
            setInputValue(e.target.value);
          }}
          value={inputValue}
        ></textarea>
      </div>
    </div>
  );
}

export default App;

Is it bad practice to have a views folder in NextJS?

hope everyone is well.

I have a quick question regarding best practice with Next.JS. As the title suggests the question is related to the way in which a next project is structured.

To get the point:

In Next.JS we have the pages folder which is responsible for rendering actual site pages within your NextJS app. For example, pages/about.tsx would render a page at https://yoursite.com/about great, that works fine.

However, a source of pain for me has been the fact that these files can end up becoming pretty big and messy as they are essentially assembly components which combine multiple components to make the page while adding route specific data to each component.

I decided to take the path of having a views folder which sits adjacent to the pages folder and has components which assemble various sections of the each page.

For example, the file pages/about.tsx would also have a folder in views (views/About) which houses various assembled sections of the page AboutIntroSection.tsx, AboutContactSection.tsx etc.

This method allows my actual route handlers to look much neater however I feel this could be a bit of a pain in the long run and could be considered to be bad practice.

Before I head down this tunnel full steam I wanted to get some opinions on this topic, namely I wanted to know peoples’ thoughts on:

  1. Using the method described above
  2. Just assembling the pages in their respective route folder
  3. Making a sort of BasePage component which takes a pageType prop and conditionally renders depending on that

I feel like the answer will be just go with 2 but, yeah, thought I would ask.

Thank you all.

Regex inside javascript string

I have a form that needs to be implemented through javascript:

var birthdayForm = '<form id="birthday_signup" class="klaviyo_gdpr_embed_Wh3QTB" style="margin-top: 40px;" action="//manage.kmail-lists.com/subscriptions/subscribe" data-ajax-submit="//manage.kmail-lists.com/ajax/subscriptions/subscribe" method="GET" target="_blank" novalidate="novalidate">'+
'<input type="hidden" name="g" value="Wh3QTB">'+
'<input type="hidden" name="$fields" value="Birthday">'+
'<input type="hidden" type="text" name="Birthday" id="final_birthday">'+
'<div class="klaviyo_field_group">'+
'<h2>Vertel ons jouw verjaardag en we zorgen voor een leuke verrassing!</h2>'+
'<input class="" style="display:none;" type="email" value="" name="email" id="k_id_email" placeholder="Your email" />'+
'<div class="klaviyo_field_group klaviyo_form_actions">'+
'<div class="klaviyo_field_group" style="margin: 10px 0;">'+
'<input id="klaviyo_form_Birthday" oninput="this.value = this.value.replace(/[^0-9/.]/g, '').replace(/(..*)./g, '$1');" placeholder="dd/mm/yyyy" maxlength="10" type="text" />'+
'<button type="submit" class="klaviyo_submit_button btn" style="margin-left: 15px;">Versturen</button>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="klaviyo_messages">'+
'<div class="success_message" style="display:none;">'+
'<p class="thank_you">Bedankt om jouw verjaardag te delen!</p>'+
'</div>'+
'<div class="error_message" style="display:none;"></div>'+
'</div>'+
'<div class="klaviyo_form_actions" style="margin: 10px 0;">'+
''+
'</div>'+
'</form>';

As you can see, the following regex is beig executed on “oninput”:

oninput="this.value = this.value.replace(/[^0-9/.]/g, '').replace(/(..*)./g, '$1');"

Unfortunately, this breaks. It’s probably not being escaped correctly. I fail to see how exactly though. Can anyone help me?

Push notice not being read

I am trying to get the push notices visible upon pressing the button, depending on your age either of the “You are of legal age” or “You are not of legal age” messages should be written out depending on the age input by the user, if all previous inputs are filled and password is correct.

Sorry for any formatting issues.

HTML:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Inlämningsuppgift</title>
    
        <script src="JSny copy.js" defer></script>
    </head>
    <body>
        <div id="errorOutput"></div>    
        <p id="output"></p>
            <div>
                <label for="UNameInput">Name Input</label>
                <input id="UNameInput" name="name" type="text">
            </div>
            <div>
                <label for="AgeInput">Age Input</label>
                <input id="AgeInput" name="age" type="number">
            </div>
            <div>
                <label for="PasswordInput">Password Input</label>
                <input id="PasswordInput" name="password" type="password">
            </div>
            <button id="button">Submit</button>
    </body>
    </html>

JS Code:

let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");

clickElement.addEventListener("click", function (e) {

    let feedback = [];
    let users = [];

    if (UNameInput.value === '' || UNameInput.value === null) {
        feedback.push('Name input missing')
    }

    else if (AgeInput.value === '' || AgeInput.value === null) {
        feedback.push('Age input missing')
    }
    else if (PasswordInput.value !== 'IHM') {
        feedback.push('Password is not valid')

    } else feedback.forEach((item, i) => {
            
        if (ageElement.value < 18) {
                feedback.push ("You are not of legal age")
            }
        else {
            feedback.push("You are of legal age")
            }
    
    }); 

    if (feedback.length > 0) {
        e.preventDefault()
        faultElement.innerText = feedback.join(", ")
    }
});

Do multiple exports of same code increase bundle size?

I have a folder called types where I store all my typescript types in the same structure as my main project. I store types that are needed in several places in this folder. This is how my types folder looks like:

enter image description here

My other components sometimes need types from several of the files in this folder, so I added index.ts files to import all files in each folder to their respective index.ts file and finally I export all the index.ts files from the main index.ts file in types folder.

This is how index.ts file in utils folder looks like:

export * from './showToast';
export * from './urlGenerator';

This is how main index.ts file looks like:

export * from './components/common';
export * from './services';
export * from './utils';

Everything works perfectly and I can import all my types from the main index.ts file but I was wondering if this exporting of the same types multiple times (once in file itself, once in index.ts file inside respective folder, once in main index.ts file) can increase the bundle size or have any bad effects. I have used this approach for some of my other folders too. So does this approach have any bad effects? I would like to hear your suggestions for structure if this structure is not good.

How do I access array with array using vueJs?

0: {id: "162e0db0-b1af-465c-b8b2-a0148dc7d67d", 
feeCategoryID: "c75b6190-7ca2-4095-9647-84e9f3790185",..}
academicYearID: 12
endAdmissionDate: "2022-03-31T00:00:00.000Z"
feeComponentClassMaps: 
0: {classID: 969, studentClasses: [{id: 969, name: "PP2 TO GRADE 1"}]}
1: {classID: 974, studentClasses: [{id: 974, name: "PP2 TO GRADE 2"}]}


1: {id: "152e0db0-b1af-465c-b8b2-a0148dc7d69fv", 
feeCategoryID: "c35b6190-7ca2-4095-9647-84e9f3790165",…}
academicYearID: 13
endAdmissionDate: "2022-03-31T00:00:00.000Z"
feeComponentClassMaps: 
0: {classID: 979, studentClasses: [{id: 979, name: "E BC NURSERY"}]}
1: {classID: 986, studentClasses: [{id: 986, name: "EG BC NURSERY"}]}

I want to fetch all name value from array index one i.e “E BC NURSERY” and “EG BC NURSERY” should be fetch in drop down.