How to change sytle properties of an element in JavaScript?

I am making a small online app that will require the user to input some options and the site will change it’s background and similar features based on their input.
However, I have not been able to change any of the document style properties through JavaScript code.

Am I missing something?

let bgType = prompt("Which type of background do you want? Color or image: ");

if (bgType == "color" || bgType == "Color") {
    let colBg = prompt("Enter the color you want");
    document.getElementById("background").style.backgroundColor = colBg; // I've tried putting default colors here for testing, but those didn't work either
} else if (bgType == "image" || bgType == "Image") {
    let imgBg = prompt("Enter the number of the image you want (1-3): ");
    document.getElementById("background").style.backgroundColor = ""; // Unfinished
}

In case it’s needed here is also the HTML and CSS code
HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>
        <title>Greeting card generator</title>
        <meta name='viewport' content='width=device-width, initial-scale=1'>
        <link rel='stylesheet' type='text/css' media='screen' href='gfx.css'>
    </head>
    <body>
        <script src='script.js'></script>
        <div id="background" class="content">
            <!-- <img src="Temp1.jpg" alt="Greeting card image"> -->
            <h1 id="Title" class="text">
                Sample title text
            </h1>
            <h2 id="Name" class="text">
                Sample name text
            </h2>
            <h3 id="Message" class="text">
                Sample message text
            </h3>
        </div>
    </body>
</html>

CSS:

html, body {
    height: 100%;
    margin: 0;
}

#background {
    width: 100%;
    min-height: 100%;
    background-image: url();
    background-color: white;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.text {
    font-family: verdana;
    text-align: center;
}

#Title {
    padding-top: 20%;
}

Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime

when I start my react project in Fedora 32 using command yarn start, shows error like this:

./src/style/base.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/style/base.scss)
Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (93)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1

my current node version is:

[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/react-admin% nvm list
        v8.17.0
       v10.24.1
->     v16.13.0
        v17.2.0
         system
default -> 8 (-> v8.17.0)

I have tried different version of node but did not fix this problem, why did this happen? what should I do to fix this problem? I did not found any package dependencies of node sass in the package.json, this is the package.json file:

{
    "name": "react-admin",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@ant-design/compatible": "1.0.8",
        "animate.css": "^3.7.2",
        "antd": "^4.0.0",
        "axios": "^0.19.0",
        "braft-editor": "^2.3.8",
        "echarts": "^4.4.0",
        "is-core-module": "2.2.0",
        "moment": "2.29.1",
        "nprogress": "^0.2.0",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-highlight-words": "0.17.0",
        "react-loadable": "^5.5.0",
        "react-redux": "^7.1.1",
        "react-router-dom": "^5.1.1",
        "react-scripts": "^3.2.0",
        "redux": "^4.0.4",
        "redux-logger": "3.0.6",
        "redux-promise-middleware": "^6.1.2",
        "redux-thunk": "^2.3.0",
        "screenfull": "^5.0.0"
    },
    "scripts": {
        "start": "react-app-rewired start",
        "build": "CI=false && react-app-rewired build",
        "test": "react-app-rewired test",
        "eject": "react-scripts eject"
    },
    "eslintConfig": {
        "extends": "react-app"
    },
    "browserslist": {
        "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
        ],
        "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
        ]
    },
    "husky": {
        "hooks": {
            "pre-commit": "lint-staged"
        }
    },
    "lint-staged": {
        "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
            "node_modules/.bin/prettier --write",
            "git add"
        ],
        "src/**/*.{css,scss,less,json,html,md,markdown}": [
            "node_modules/.bin/prettier --write",
            "git add"
        ]
    },
    "devDependencies": {
        "@babel/helper-builder-react-jsx": "^7.12.13",
        "babel-plugin-import": "^1.12.2",
        "customize-cra": "^0.8.0",
        "husky": "^3.0.9",
        "lint-staged": "^9.4.2",
        "sass": "1.37.0",
        "prettier": "^1.18.2",
        "react-app-rewired": "^2.1.4"
    }
}

React Force horizontal scrolling as vertical scroll when reaching element view

I’ve been trying to achieve this effect of default horizontal scrolling when reaching element’s view.
I still could not find some decent way to implement it correctly, for now I was only able to achieve it with pure CSS (the problem is – it doesn’t scrolled horizontal correctly, I need to click on the element so it will be aware I’m in the right view.
This is my code for now –

::-webkit-scrollbar {
      width: 1px;
      height: 1px;
    }

    ::-webkit-scrollbar-button {
      width: 1px;
      height: 1px;
    }


    .test {
      position: absolute;
      display: block;
      top: 0;
      left: 0;
      width: calc(250px + 1px);
      max-height: 750px;
      margin: 0;
      padding-top: 1px;
      background: #abc;
      overflow-y: auto;
      overflow-x: hidden;
      transform: rotate(-90deg) translateY(-250px);
      transform-origin: right top;
      padding: 250px 0 0 0;
    }

    .test div {
      display: block;
      padding: 5px;
      background: #cab;
      transform: rotate(90deg);
      transform-origin: right top;
      width: 250px;
      height: 250px;
      margin: 10px 0;
    }
<div class="test">
      <div>div</div>
      <div>div</div>
      <div>div</div>
      <div>div</div>
      <div>div</div>
      <div>div</div>
      <div>div</div>
      <div>div</div>
    </div>

I’d love to know if there is any way to make the scrolling automatically start horizontally as I reach the view, and if that’s not possible I’d love to know how would you implement it with JS in React.
Thank you!

event not firing after some clicks

i don’t understand after certain clicks add element is not firing , it just stops, my count variables are working fine but don’t know what seems to be the issue here,

 $(document).on('click','.add-role-btn',function(e){
                    console.log('working')
                    if (add_count < 3){
                        $('.role-name-container').append(
                            $('<input type="text" name="role_name" class="form-control mt-3" placeholder="Role name">')
                        )
                     }
                     add_count += 1;
                    
    
                })

            $(document).on('click','.delete-role-btn',function(e){
                console.log('working')
                let last_elem = $('.role-name-container').children().last();
                
                if ($('.role-name-container').first().not(last_elem))
                {
                    last_elem.remove()
                }
                add_count -= 1;

               
                
            })

Take a screenshot of a new tab using Puppeteer

I’m using puppeteer to click on a link that opens a new tab, and take a screenshot of this tab using :

const pages = await browser.pages()
const new_page = pages[pages.length-1]
await new_page.screenshot()

but I made some research and I found that browser.pages() contains only the default blank pages and my current tab but not the new one.

Hence, when I take a screenshot, it takes a screenshot of the current tab.
To give you some context, the new tab is a PHP url and it display a pdf file. I tried waitForNavigation, bringToFront and nearly every possible console.log().

Does anyone know how to help me ?

How to change property with a condition inside React.useState()

I have a component that uses React.useState to keep a property named available
and what I want to do is to change its value to true with a conditional statement, so that my component gets rendered based on that condition, but I can’t set up a conditional statement inside React.useState. I tried changing it in my other component with a conditional statement:

  const [isUserLogged] = React.useState(true);
  const arrowDir = props['data-expanded']
    ? 'k-i-arrow-chevron-down'
    : 'k-i-arrow-chevron-right';

  if (isUserLogged === true) {
    props.available === true;
  }

But that didn’t work too. How can I achieve this with a conditional statement? Here is my entire code:

import * as React from 'react';
import { withRouter } from 'react-router-dom';
import {
  Drawer,
  DrawerContent,
  DrawerItem,
} from '@progress/kendo-react-layout';
import { Button } from '@progress/kendo-react-buttons';

const CustomItem = (props) => {
  const { visible, ...others } = props;
  const [isUserLogged] = React.useState(true);
  const arrowDir = props['data-expanded']
    ? 'k-i-arrow-chevron-down'
    : 'k-i-arrow-chevron-right';

  if (isUserLogged === true) {
    props.available === true;
  }

  return (
    <React.Fragment>
      {props.available === false ? null : (
        <DrawerItem {...others}>
          <span className={'k-icon ' + props.icon} />
          <span className={'k-item-text'}>{props.text}</span>
          {props['data-expanded'] !== undefined && (
            <span
              className={'k-icon ' + arrowDir}
              style={{
                position: 'absolute',
                right: 10,
              }}
            />
          )}
        </DrawerItem>
      )}
    </React.Fragment>
  );
};

const DrawerContainer = (props) => {
  const [drawerExpanded, setDrawerExpanded] = React.useState(true);
  const [isUserLogged] = React.useState(true);

  const [items, setItems] = React.useState([
    {
      text: 'Education',
      icon: 'k-i-pencil',
      id: 1,
      selected: true,
      route: '/',
    },
    {
      separator: true,
    },
    {
      text: 'Food',
      icon: 'k-i-heart',
      id: 2,
      ['data-expanded']: true,
      route: '/food',
    },
    {
      text: 'Japanese Food',
      icon: 'k-i-minus',
      id: 4,
      parentId: 2,
      route: '/food/japanese',
    },
    {
      text: 'Secret Food',
      icon: 'k-i-minus',
      id: 5,
      parentId: 2,
      route: '/food/italian',
      available: false,
    },
    {
      separator: true,
    },
    {
      text: 'Travel',
      icon: 'k-i-globe-outline',
      ['data-expanded']: true,
      id: 3,
      route: '/travel',
    },
    {
      text: 'Europe',
      icon: 'k-i-minus',
      id: 6,
      parentId: 3,
      route: '/travel/europe',
    },
    {
      text: 'North America',
      icon: 'k-i-minus',
      id: 7,
      parentId: 3,
      route: '/travel/america',
    },
  ]);

  const handleClick = () => {
    setDrawerExpanded(!drawerExpanded);
  };

  const onSelect = (ev) => {
    const currentItem = ev.itemTarget.props;
    const isParent = currentItem['data-expanded'] !== undefined;
    const nextExpanded = !currentItem['data-expanded'];
    const newData = items.map((item) => {
      const {
        selected,
        ['data-expanded']: currentExpanded,
        id,
        ...others
      } = item;
      const isCurrentItem = currentItem.id === id;
      return {
        selected: isCurrentItem,
        ['data-expanded']:
          isCurrentItem && isParent ? nextExpanded : currentExpanded,
        id,
        ...others,
      };
    });
    props.history.push(ev.itemTarget.props.route);
    setItems(newData);
  };

  const data = items.map((item) => {
    const { parentId, ...others } = item;

    if (parentId !== undefined) {
      const parent = items.find((parent) => parent.id === parentId);
      return { ...others, visible: parent['data-expanded'] };
    }

    return item;
  });
  return (
    <div>
      <div className="custom-toolbar">
        <Button icon="menu" look="flat" onClick={handleClick} />
        <span className="title">Categories</span>
      </div>
      <Drawer
        expanded={drawerExpanded}
        mode="push"
        width={180}
        items={data}
        item={CustomItem}
        onSelect={onSelect}
      >
        <DrawerContent>{props.children}</DrawerContent>
      </Drawer>
    </div>
  );
};

export default withRouter(DrawerContainer);

How to properly structure logic in redux?

There is an action to update an item:

reducers: {
  ITEM_UPDATED: (state) => {
    ...someCode...
  }
}

Then it becomes necessary to update not one element, but several, which solution would be more correct here:

  1. Create thunk for updating several elements and from there call the update of each one by one:
const updateItems = () => (dispatch) => {
  const items = axios.get('...');
  items.forEach(( item ) => dispatch(ITEM_UPDATED, item))
}
  1. Move the handler for updating the element into a separate function and reuse it.
const handleItemUpdated = (state) => {
  ...
}

reducers: {
  ITEM_UPDATED: (state, item) => handleItemUpdated(state, item);
  ITEMS_UPDATED: (state, items) => {
    items.forEach(( item) => handleItemUpdate(state, item));
  }
}

How to use spinner and then display a component after submit button?

So I am building this project using ChakraUI and ReactJS.
So in this UploadImage component, what I wanna do is, when you choose a file and then hit the Upload button, the spinner will load while the data is being fetched. After it is finished fetching the data, the loading is going to be false and it will render the component.
But currently it is rendering component initially and after you submit the file it renders the DisplayImage component.
So how to implement the spinner component properly?

My current code is the following:

function UploadImage() {
  const [selectedFile, setSelectedFile] = useState(null);
  const [error, setError] = useState(null);
  const [inputImage, setInputImage] = useState(null);
  const [outputImage, setOutputImage] = useState(null);
  const [isSubmit, setIsubmit] = useState(false);
  const [isLoading, setIsloading] = useState(true);
  const fileUploadHandler = () => {
    const fd = new FormData();
    fd.append("file", selectedFile, selectedFile.name);
    axios
      .post(`/api/predict`, fd)
      .then((res) => {
        setIsubmit(true);
        setInputImage(res.data.image);
        setOutputImage(res.data.mask);
        selectedFile(null);
        setError(null);
        setIsloading(false);
      })
      .catch((error) => {
        console.log(error);
        setSelectedFile(null);
        setError(error.data);
      });
  };

  const fileData = () => {
    if (selectedFile) {
      if (
        selectedFile.type === "image/jpeg" ||
        selectedFile.type === "image/png"
      ) {
        return (
          <div>
            {error && <div>file too large!!</div>}
            <Button
              colorScheme='teal'
              size='sm'
              onClick={() => fileUploadHandler()}
            >
              Upload!
            </Button>
          </div>
        );
      } else {
        return (
          <div>
            <h4>Please choose an image to upload</h4>
          </div>
        );
      }
    } else {
      return (
        <div>
          <h4>Choose Photos</h4>
        </div>
      );
    }
  };

  return (
    <div>
      <input type='file' onChange={(e) => setSelectedFile(e.target.files[0])} />
      {fileData()}
      {isSubmit && isLoading === false ? (
        <DisplayImage inputImage={inputImage} outputImage={outputImage} />
      ) : (
        <Spinner />
      )}
    </div>
  );
}
export default UploadImage;

Select an element having conditional render, on the beginning of the code in react.js

I’ve made 2 popup div in react. On the first page load, first popup is visible but i’ve set the opacity of second popup to 0. I’m handling this with a class ‘hide’. And i’m placing this hide class on the second popup based on a state. What i’m trying to achieve here is that i want to select a button having a class of ‘evil-btn’ that is present on the second popup. And add some event listeners to that button. But i’m not able to select that button, as a global variable. It’s returning null. So can anyone suggest me a way how i can select this button in the global scope..?? Below is the code for my Popup component.

import React, { useEffect, useRef, useState } from "react"

function Popup() {
  const [isSecondActive, setIsSecondActive] = useState(false)
  const [firstBtn, setFirstBtn] = useState(true)
  const [secondBtn, setSecondBtn] = useState(false)
  const container2_ref = useRef(null)
  console.log(container2_ref)

  const OFFSET = 100

  const handleMouseOver = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "NO") {
      setFirstBtn(!firstBtn)
      setSecondBtn(!secondBtn)
    }
  }

  const handleClick = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }
  }

  const handleSecondClick = (e) => {
    console.log(e.target.dataset.name)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }

    if (e.target.innerText === "NO") {
      alert(
        "I hate you, you clicked me so hard, I'm going and closing this window"
      )
      // window.close()
    }
  }

  var evilBtn = document.querySelector(".evil-btn")

  document.addEventListener("mouseover", (e) => {
    const x = e.pageX
    const y = e.pageY
    const buttonBox = evilBtn.getBoundingClientRect()
    // console.log("x", x)
    // console.log("y", y)
    let horizontalDistanceFrom = distanceFromBtn(
      buttonBox.x,
      x,
      buttonBox.width
    )
    let verticalDistanceFrom = distanceFromBtn(buttonBox.y, y, buttonBox.height)

    const verticalOffset = buttonBox.height + OFFSET / 2
    const horizontalOffset = buttonBox.width + OFFSET / 2

    if (
      Math.abs(
        horizontalDistanceFrom <= horizontalOffset &&
          Math.abs(verticalDistanceFrom <= verticalOffset)
      )
    ) {
      setButtonPosition(
        buttonBox.x + (horizontalOffset / horizontalDistanceFrom / 2) * 10,
        buttonBox.y + (verticalOffset / verticalDistanceFrom / 2) * 10
      )
    }
  })

  const setButtonPosition = (left, top) => {
    console.log(evilBtn)
    evilBtn.style.left = `${left}px`
    evilBtn.style.top = `${top}px`
  }

  const distanceFromBtn = (buttonPosition, mousePosition, buttonSize) => {
    return buttonPosition - mousePosition + buttonSize / 2
  }

  return (
    <div className='container'>
      <div className='popup'>
        <section className='section-top'>
          {/* CONTAINER 2 START */}
          {
            <div
              ref={container2_ref}
              className={`container second-container container-2 ${
                isSecondActive ? "" : "hide"
              }`}
            >
              <div className='popup'>
                <section className='section-top'>
                  <button
                    onClick={() => setIsSecondActive(false)}
                    className='close-btn'
                  >
                    X
                  </button>
                </section>
                <section className='section-middle'>
                  <h2 className='heading-msg'>
                    Do you really want to quit? But first tell me are you
                    dumb..??
                  </h2>
                </section>
                <div className='btn-containers'>
                  <button
                    data-name='second-yes'
                    onClick={handleSecondClick}
                    className='btn yes-2'
                  >
                    YES
                  </button>
                  <button
                    data-name='second-no'
                    onClick={handleSecondClick}
                    className='btn no-2 evil-btn'
                  >
                    NO
                  </button>
                </div>
              </div>
            </div>
          }
          {/* CONTAINER 2 END */}
          <button onClick={() => setIsSecondActive(true)} className='close-btn'>
            X
          </button>
        </section>
        <section className='section-middle'>
          <h2 className='heading-msg'>Are You Dumb..??</h2>
        </section>
        <div className='btn-container'>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-yes'
            className='btn yes-1'
          >
            {firstBtn ? "YES" : "NO"}
          </button>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-no'
            className='btn no firstNo'
          >
            {secondBtn ? "YES" : "NO"}
          </button>
        </div>
      </div>
    </div>
  )
}

export default Popup

Toogle active class using getElementById

I am trying to change class from none to active using document.getElementById but it is just adding active not removing it.

page.html

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`).className += "content active";
  collapseModel[0].classList.toggle("active")
}
.content {
  padding: 10px 20px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.content.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button onclick="toggleIt();">Open</button>

<div class="content" id="collap_id">
  Here will be all the details
</div>

When I click on toggle it then it is opening but not closing , it is also showing "Uncaught TypeError: Cannot read properties of undefined (reading 'toggle')"

I have tried many times but it is not toggling.

Javascript module in nuxt [duplicate]

i am learning how to build a js module and upload to npm and install back into nuxt and try to use the function inside. trying to understand the proccess to build a module. but i keep getting error, i try to simple the module much as possible can anyone tell me what i miss out ?

module – dayuntilxmas
github enter link description here

dayuntilxmas

  • README.md
  • index.js
  • package.json

index.js

export function greetPerson(name) {
    return `Hello ${name}`;
}

nuxt/pages/index.vue

<template>
    <div>
        <h1>this is plugins test framework</h1>
    </div>
</template>

<script>
    import {
        greetPerson
    } from 'dayuntilxmas'

    export default {
        data() {
            const greet = greetPerson()
            return {
                greet
            }
        },
        mounted() {
            console.log(this.greet('jade'))
        }
    }
</script>

so what do i missout ? i see some said need to include a html file inside module, but isit needed for some reason ?

the error it return was “Unexpected token ‘export'”

How to get the first day of the next month in JavaScript

I need to get the first day of the next Month for a datePicker in dd/mm/yyyy format.

how can i do it?

i have this code :

var now = new Date();
if (now.getMonth() == 11) {
  var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
  var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

console.log(current)

but it’s give this :

Sat Jan 01 2022 00:00:00 GMT+0200 

i need it like this 01/01/2022

any help here =)?

Why well-know symbols are in Symbol and not in Reflect API

I don’t understand one thing about well-known symbols in Javascript. What is the reason of putting those well-known symbols into Symbol instead of Reflect API? For me seems that the right place for them is the Reflect API as the Reflect API is made for metaprogramming, particularly for reflection and particularly for introspection and self-modification? Does anyone knows the reason of doing so?