Automatically generating and display color code after pressing button

I have a button “White color” and I am curious how can I make the text under the button “#White” automatically generate after clicking on it and not be hardcoded as in the example I have below. For example showing as “#000000” after pushing the button.

const buttonColor = document.querySelector("[data-buttColor]");
const pEl = document.querySelector("[data-colorCode]");
const background = document.querySelector("[data-background]");

const buttonColorWhite = document.querySelector("[data-buttColorWhite]");
const buttonColorBlack = document.querySelector("[data-buttColorBlack]");

buttonColor.addEventListener("click", () => {
  let color = "#";
  color += Math.random().toString(16).slice(2, 8);
  background.style.backgroundColor = color;
  pEl.innerText = color;
  console.log(color)
})

buttonColorWhite.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "white";
  let color = "#white";
  pEl.innerText = color;
  console.log(color)

})

buttonColorBlack.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "black";
  let color = "#black";
  pEl.innerText = color;
  console.log(color)
})
<div class="text-center text-white animate__animated animate__flipInX">
  <button data-buttColor class="btn btn-primary btn-lg mt-3">Random color</button>
  <button data-buttColorWhite class="btn btn-primary btn-lg mt-3">White color</button>
  <button data-buttColorBlack class="btn btn-primary btn-lg mt-3">Black color</button>
  <p data-colorCode>The color is</p>
  <p data-background>&nbsp;</p>
</div>

Remove the Operator Signs in textbox [closed]

I’m creating a calculator using the JS, I created buttons so it will concatenate the numbers before clicking the operators. I want to use the eval() funtion to compute the numbers in the textbox but the Operator signs must not be displayed in the textbox. So instead of 2 +1 the result in the textbox will be 2 >>operator button clicked >> 1 then the result would be 3 Any Help? Thanks

<div class = btnDiv1>               
                <button onclick="view('7')">7</button>
                <button onclick="view('8')">8</button>
                <button onclick="view('9')">9</button>
                <button onclick="viewOp('*')">X</button>
                <button onclick="btnClear('')">C</button>
                <br>

                <button onclick="view('4')">4</button>  
                <button onclick="view('5')">5</button>
                <button onclick="view('6')">6</button>
                <button onclick="viewOp('/')">/</button>
                <button onclick="view('')">H</button>
                <br>

                <!-- Create another div so align equal sign buttons -->     
                <div class=btnDiv2>
                    <button onclick="view('1')">1</button>
                    <button onclick="view('2')">2</button>
                    <button onclick="view('3')">3</button>
                    <button onclick="viewOp('-')">-</button>
                    <button onclick="Compute(' ')" class = "btnCmp">=</button>
                    <br>

                    <button onclick="viewNegate('')">+/-</button>
                    <button onclick="view('0')">0</button>
                    <button onclick="view('.')">.</button>
                    <button onclick="viewOp('+')">+</button>
                    <br>                    
                </div>          
            </div>

Javascript
// passed the value of the clicked button
function view(num)
{   
    document.getElementById("txtResult").value+= num;
}

How to generate randome Integers in react js without repeating [duplicate]

When the user press the button next function NextQuestion will be called this function should be able to loop randomly through data (array of objects with two properties name and description) without repeating the same elements each time the user press the button next and then after it finishes showing all elements it should call another function to alert me (for future developing)

import React, {useContext} from 'react';
import CheckAnswer from './CheckAnswer';
import { RandomIntContext } from '../Contexts/RandIntContext';
import { ExamStateContext } from '../Contexts/ExamStateContext';
import { DataContext } from '../Contexts/DataContext';

import { ButtonGroup, ToggleButton, Button } from 'react-bootstrap';

const NextQuestion = () => {

    const {randInt, setRandInt} = useContext(RandomIntContext);
    const {examState, setExamState} = useContext(ExamStateContext);
    const {data} = useContext(DataContext);

    const nextQuestion = () => {
        setRandInt(Math.floor(Math.random() * data.length));
    }

    return (
        <div className="next_cont">
            <div>
                <ButtonGroup>
                    <ToggleButton type="radio" variant="outline-dark" value="word" size="md" checked= {examState === "word"} onClick={(e) => setExamState("word")}> Word</ToggleButton>
                    <ToggleButton type="radio" variant="outline-dark" value="description" size="md" checked= {examState === "description"} onClick={(e) => setExamState("description")}> Description</ToggleButton>
                </ButtonGroup>
            </div>

            <h3>{examState === "word" ? "What is the description of the word" : "What is the word that describes"} {data[randInt][examState]}</h3>

            <CheckAnswer/>

            <div>
                <Button variant="outline-dark" onClick={nextQuestion}>Next</Button>
            </div>
        </div>
    )
}

export default NextQuestion

Can’t get user id in TS file in Angular

Can’t get user id in TS file in Angular _id: undefined
Http failure response for http://localhost:5000/users/undefined

Service File:
UpdateUser(userID:any,data : any){
return this.httpClient.put(${environment.APIURL}/users/${userID},JSON.stringify(data),this.options)
.pipe(map((res:any)=>{
return res
}))
}

How to transfer custom SPL token by ‘@solana/web3.js’ and ‘@solana/sol-wallet-adapter’

Hello I am trying to transfer a custom SPL token with the solana-wallet adapter.
However i am having trouble getting the wallet’s secret key/signing the transaction.

I’ve looked at these answers for writing the transfer code but i need to get the Singer and i have trouble figuring out how with solana-wallet adapter. These examples hardcode the secret key and since i’m using a wallet extension this is not possible.

How can you transfer SOL using the web3.js sdk for Solana?

How to transfer custom token by ‘@solana/web3.js’

according to this issue on the webadapter repo https://github.com/solana-labs/wallet-adapter/issues/120 you need to:

  1. Create a @solana/web3.js Transaction object and add instructions to it
  2. Sign the transaction with the wallet
  3. Send the transaction over a Connection

But i am having difficulty finding examples or documentation as to how to do step 1 and 2.

const SendTransaction: React.FC<Props> = ({ children }) => {
    const { connection } = useConnection()
    const { publicKey, sendTransaction } = useWallet()

    const onSendSPLTransaction = useCallback(
        async (toPubkey: string, amount: number) => {
            if (!toPubkey || !amount) return
            const toastId = toast.loading('Processing transaction...')

            try {
                if (!publicKey) throw new WalletNotConnectedError()
                const toPublicKey = new PublicKey(toPubkey)
                const mint = new PublicKey('Mint address')
                const payer = '????' // how to get this Signer
                const token = new Token(connection, mint, TOKEN_PROGRAM_ID, payer)
                const fromTokenAccount = await token.getOrCreateAssociatedAccountInfo(publicKey)
                const toTokenAccount = await token.getOrCreateAssociatedAccountInfo(toPublicKey)

                const transaction = new Transaction().add(
                    Token.createTransferInstruction(
                        TOKEN_PROGRAM_ID,
                        fromTokenAccount.address,
                        toTokenAccount.address,
                        publicKey,
                        [],
                        0
                    )
                )

                const signature = await sendTransaction(transaction, connection)

                const response = await connection.confirmTransaction(signature, 'processed')
                console.log('response', response)
                toast.success('Transaction sent', {
                    id: toastId,
                })
            } catch (error) {
                toast.error(`Transaction failed: ${error.message}`, {
                    id: toastId,
                })
            }
        },
        [publicKey, sendTransaction, connection]
    )

    return <>{children(onSendSPLTransaction)}</>
}

Optimal setting of triggers in React (similar to Google maps)

I am new to React and I have a question.

I have a conditionally infinite space in 4 directions implemented through a transform translate, like Google maps. I can also move in four directions. However, I have a question about how to implement a trigger to load new objects and simultaneously delete old objects in the React.

I made an implementation via observer, in the form of four divs in all directions. I didn’t really like this solution because of the constant excessive manipulation of the DOM tree, in the form of rebuilding divs after loading objects.

I also tried to make an implementation through a coordinate tracking transformer to calculate the moment of loading objects. But with this implementation, I will need to use setInterval. And that’s not cool (probably).

If you have any idea how it is implemented on Google maps?
Scheme

How to search number from html table using javascript?

I am having difficulty searching numbers from the HTML table using javascript. What I want to do, if I enter 500 then the results should be 500 and numbers that are also greater than 500. F
I checked other StackOverflow questions but it is not answered as I expected. Can anyone help me, please?

HTML CODE:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Number</th>
    <th style="width:40%;">Alphabats Code</th>
  </tr>
  <tr>
    <td>500</td>
    <td>ANAA</td>
  </tr>
  <tr>
    <td>520</td>
    <td>MNAAA</td>
  </tr>
  <tr>
    <td>400</td>
    <td>INNA</td>
  </tr>
  <tr>
    <td>200</td>
    <td>OISSS</td>
  </tr>
  <tr>
    <td>500</td>
    <td>QIIWS</td>
  </tr>

</table>

JavaScript Code – or Example, if I search 500 then the result should come 500, 520. I mean must be greater then and equal to the number which I put in search field.

function myFunction(){

   let filter = document.getElementById('myInput').value;
   let myTable = document.getElementById('myTable');
   let tr = myTable.getElementsByTagName('tr');
   for(var i=0; i<tr.length; i++)
   {
     let td = tr[i].getElementsByTagName('td')[0];
     if(td)
     {
       let textValue = td.textContent || td.innerHTML;
      if(textValue >= filter  )
      {

        tr[i].style.display = "";

      }
      else 
      {
        tr[i].style.display = "none";
      
      }

     }

   }


}

how can i run hosted project in local, used redirect uri,clientid after making an account on spotify but getting error

i cloned https://github.com/espitiaandres/studyfi and i want to run it in local. i have made my account on spotify developer and took redirecturi and client id and wrote in config.js but localhost is refusing to connect


    ```const authEndpoint = "http://accounts.spotify.com/authorize";
    // const clientId = "53bcecd410634483b53########";
    const clientId = "e6690d4f0b734a6c89336c#######";
    const redirectUri = "http://localhost:8080/callback";                    // dev redirectUri
    // const redirectUri = "https://www.andres-espitia.com/studyfi/";      // prod redirectUri
    const scopes = [
        "user-top-read",
        "user-read-currently-playing",
        "user-read-playback-state",
        "user-modify-playback-state",
        "playlist-read-private"
    ];
    
    export { 
        authEndpoint, 
        clientId, 
        redirectUri, 
        scopes 
    }```
in app.js the following code is written
app.js

    const getCurrentlyPlaying = (token) => {
        axios({
            method: 'get',
            url: 'https://api.spotify.com/v1/me/player',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        }).then(({ data }) => {
            if(!data) {
                setData(data);
                return;
            }
token.js 

in token.js the following code is written
there is probably authorization error too
export const setToken = (token) => ({
type: ‘SET_TOKEN’,
token
});

export const startSetToken = (token = "") => {
    return (dispatch, getState) => {
        return dispatch(setToken(token));
    }
}

getting this link after clicking login
http://localhost:8080/callback#access_token=BQBR6jxgnBEWYYIuRjsvnxkQ-RqzVFRZ7JR1Q_9F3XWHhExQ7EaWTTj1z5ZzHXu2onRE8xRvRBHWz0qCB5Z776gHfejbXogxvkwaXDQgZGGFb4ezvHSM_87Ofy9wfZJD1_DZkehZ9NeEMehXeDShZaOVFo4DL-hMfaWNcDa9oQTQz-tJ-7UZcjiw&token_type=Bearer&expires_in=3600

how do i fix this and make this project run on my local

JavaScript: mouseover function not working in iframe

I have an iFrame and what I want to do is to change the height and width of the div when the mouse hovers around the elements inside the iframe, but the mouseover function is not working. What am I missing?

<html>
  <body>
    <div>
      <iframe
        id="zzz"
        width="500"
        height="500"
        srcdoc="<html><body><h1>hello</h1><button>click</button><div id='abcd' style='background: red; width: 300px; height: 300px;'></div></body></html>"
      ></iframe>
    </div>

    <script>
      window.addEventListener("load", () => {
        var my_iframe = document.getElementById("zzz").contentWindow.document;
        div = my_iframe.getElementById("abcd");
        div.style.background = "blue"; //just for testing

        my_iframe.addEventListener("mouseover", function (e) {
          elem = e.target;
          var rect = elem.getBoundingClientRect();
          w = rect.width;
          h = rect.height;
          div.style.width = w;
          div.style.height = h;
        });
      });
    </script>

  </body>
</html>

How to call multiple components into one component in Vuejs?

  • components/a/inputone.vue
<template>
  <div><input type="checkbox" v-model="checked" />one</div>
</template>

<script>
export default {
  name: "inputone",
  components: {},
  data() {
    return {};
  },
};
</script>
  • components/b/inputtwo.vue
<template>
  <div><input type="checkbox" v-model="checked" />two</div>
</template>

<script>
export default {
  name: "inputtwo",
  components: {},
  data() {
    return {};
  },
};
</script>
 - **components/maincontent/maincontent.vue**

<template>
  <div>
    <div class="container" id="app-container" v-if="!checked">
      <p>Text is visible</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "maincontent",
  components: {},
  data() {
    return {
      checked: false,
    };
  },
  methods: {
    hidecont() {
      this.checked = !this.checked;
    },
  },
};
</script>

I have three components called inputone(contains checkbox with v-model),inputtwo(contains checkbox with v-model),maincontent.(having some content and logic), So when user click on checkboxes from either one checckbox(one,two). i schould hide the content.

Codesanfdbox link https://codesandbox.io/s/crimson-fog-wx9uo?file=/src/components/b/inputtwo.vue

Why is this Javascript ‘if’ statement not working?

I am trying to create an image viewer in javascript. So, there’s this function where I am decreasing the size of image when ‘-‘ button is pressed or mouse wheel is scrolled downwards. But after the image’s height goes below 10px, I can’t enlarge it back anymore. So, to tackle that issue, I thought of putting an if statement where it’ll check the height of the image and won’t decrease the size if it’s not above 10px. But, that if statement is not working. And I can’t figure out why.

Below is a piece of my code. I tried to put an console.log() to check if it’s going into the if statement or not. But, it’s not going.

function decrease_image(){
    var img = new Image();
    img = image_viewer_pics[current_viewer_image];
    
    if (img.style.height < "100%"){
        img.style.margin = "auto 0px";
    }

    if (img.style.height > "10px"){
        img.height = img.height / 1.1;
        console.log("greater than 10px");
    }
    
}

Div cannot be center aligned

Problem

When I try to use the code (see below), the div is only centered when I use width: 100px;.

<div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto;">

Screenshot from the website

Since I want to assign a much longer width to the text and set the width to 500px, the div is no longer centered.