How to store a newly created element to localStorage or Cookie with Javascript?

I am making an idle clicker game for fun, and I encountered a problem.

What I want to happen is when the image is clicked and the clickCounter is over one, the new image element is created. No problem here, the main problem is saving the image. If the user refreshes the page, I want the created element to still be there. I have tried using outerHTML and following some other Stack Overflow forum questions but I could never get a proper solution to this problem.

 function oneHundThou() {

   var countvar = document.getElementById("clickCounter")
    if(document.getElementById("clickCounter").innerHTML > 1) {
      alert("Achievement! 1 pat!")
      
      var achievement1k = document.createElement("img");
     

      // create a cookie so when the user refreshes the page, the achievement is shown again 

      document.cookie = "achievement1k=true";
      achievement1k.src = "https://c.pxhere.com/images/f2/ec/a3fcfba7993c96fe881024fe21e7-1460589.jpg!d";
      
      achievement1k.style.height = "1000px"
      achievement1k.style.width = "1000px"
      achievement1k.style.backgroundColor = "red"
      
      document.body.appendChild(achievement1k);
      oneHundThou = function(){}; // emptying my function after it is run once instead of using a standard switch statement
    }
    else {
      return
    }

  }
  oneHundThou();
  

I am aware that there is another post that is similar to this, however, my answer could not be answered on that post.

Full code is here: https://code.sololearn.com/Wwdw59oenFqB
Please help… thank you.

Can I encode secret data into a media file?

  1. The file can be an audio file (mp3, aiff), a video (mp4) or an image (png, jpg).
  2. The encoded data will be a uuid string
  3. The encoded data should obviously not affect the content of the media file itself
  4. I want to be able to later extract the uuid from that file
  5. I do not want the encoded data to be extractable by anyone else

Is this possible ? If yes, could you provide me with (at least) some hints on how to go about it?

Thank you

How to import composables into server/api in Nuxt 3

I just unified a useSupabase composable to remove duplicate code and to have access to the supabase context.

But I get an error when I import the composable into the server/api folder:

message “useSupabase is not defined”

// composables/useSupabase.js
import { createClient } from '@supabase/supabase-js'
const useSupabase = () => {
  const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)
  return {
    supabase
  }
}
export default useSupabase
// server/api/login.js
export default async (event) => {
  const body = await useBody(event)
  const { supabase } = useSupabase()

  const { user } = await supabase.auth.signUp({
    email: body.email,
    password: body.password
  })
  return user
}

Is there a way to import the composable into the endpoint?

why do i have to double click to render a component?

i want to display component once i click the view icon. Somehow i have to double click to display the component. Whenever I click the view icon it sets the isViewing to be true and the component gets displayed under the Table container. I declaired viewId and setViewId on App.js and set up useContext file so that i can use the state in different components

import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import RemoveRedEyeOutlinedIcon from '@mui/icons-material/RemoveRedEyeOutlined';
import ClearOutlinedIcon from '@mui/icons-material/ClearOutlined';
import { useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { collection, deleteDoc, doc, onSnapshot } from 'firebase/firestore';
import { db } from '../../firebase';
import { Link } from 'react-router-dom';
import ViewTicket from '../viewTicket/ViewTicket';
import { UserContext } from '../../Contexts/UserContext';


const Tables = () => {
    const { viewId, setViewId } = useContext(UserContext)
    const [data, setData] = useState([]);
    const [isViewing, setIsViewing] = useState(false);

    useEffect(() => {

        const unsub = onSnapshot(collection(db, "invoices"), (snapshot) => {
            let list = [];
            snapshot.docs.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data() });
            })

            setData(list)


        }, (err) => {
            console.log(err)
        });

        return () => {
            unsub();
        }

    }, [])

    const deleteData = async (id) => {
        try {
            await deleteDoc(doc(db, "invoices", id));
            setData(data.filter((item) => item.id !== id));
        } catch (err) {
            console.log(err)
        }
    }




    return (
        <div className="conatainer">
            <TableContainer component={Paper} className="table">
                <Table sx={{ minWidth: 650 }} aria-label="simple table">
                    <TableHead>
                        <TableRow>
                            <TableCell className="tableCell">Subject</TableCell>
                            <TableCell className="tableCell">Fullname</TableCell>
                            <TableCell className="tableCell">Email</TableCell>
                            <TableCell className="tableCell">Date</TableCell>
                            <TableCell className="tableCell">Action</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {data.map((item) => (
                            <TableRow key={item.id}>
                                <TableCell className="tableCell">{item.subject}</TableCell>
                                <TableCell className="tableCell">{item.fullname}</TableCell>
                                <TableCell className="tableCell">{item.email}</TableCell>
                                
                                <TableCell className="tableCell">
                                    <RemoveRedEyeOutlinedIcon onClick={() => {
                                        setViewId(item.id)
                                        setIsViewing(true);
                                    }} className="viewButton" />
                                    <ClearOutlinedIcon className="deleteButton" onClick={() => deleteData(item.id)} />
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
            <div>
                {!isViewing ? null :
                    <ViewTicket/>
                }
            </div>
        </div>

    )
}

export default Tables

this is what i have for component. It takes the viewId to get the document details from the firebase. Then it displays the subject and email.

import { useState, useEffect, useContext } from 'react';
import { doc, getDoc } from 'firebase/firestore';
import { db } from '../../firebase';
import { UserContext } from '../../Contexts/UserContext';

const ViewTicket = () => {
    const { viewId, setViewId } = useContext(UserContext)
    const [tempData, setTempData] = useState("");

    useEffect(() => {
        if (viewId) {
            const getUserData = async () => {
                const dataRef = doc(db, "invoices", viewId);
                const docSnap = await getDoc(dataRef);

                if (docSnap.exists()) {
                    setTempData(docSnap.data());
                } else {
                    // doc.data() will be undefined in this case
                    console.log("No such document!");
                }
            }
            viewId && getUserData();
        } else {
            console.log('id does not exist')
        }
    }, [])


    return (
        <div className="single">
            <div className="singleContainer">
                <div className="details">
                    <h1>{tempData.subject}</h1>
                    <p>{tempData.email}</p>
                </div>
            </div>
        </div>
    )
}

export default ViewTicket

Show users by “location_user” in laravel-8

I have a problem with showing members based on locations,

My problem is that it displays user only, not the user’s associated with the locations

I want the member to show him only the members in the locations it is linked in table (location_user)

I know the problem is from location_user’, ‘location_user.user_id’, ‘=’, ‘users.id’

But I want the link is smart and I don’t want to add a column in the member list with the name location_id

Because I want multiple locations

This is data of UsersController.php

$data = User::leftjoin('location_user', 'location_user.user_id', '=', 'users.id')
->where('location_user.user_id', auth()->user()->id)
->leftjoin('locations', 'locations.id', '=', 'location_user.location_id')
->where('locations.status', '1')
->select('users.*',)
->orderBy('status', 'DESC')->get();

users table

enter image description here

location_user table

enter image description here

locations table

enter image description here

Can anyone help me?

Thanks.

To loop over an image folder and display all images using React Js

I have been battling this issue. I was able to do this using Javascript but couldn’t implement it on React. This is the challenge.

In JS, I used this code:

images.forEach((img, idx) => {
    img.style.backgroundImage = `url(./images/${idx + 1}.jpg)`;
  });

–to iterate over the folder ‘images’ and display all images in sequence. The idea was to scroll the images horizontally (full JS code below at the end of this description). I have tried to do the same thing on React js but couldn’t figure a way out. I’d tried the same code on JSX but didn’t work. I needed a single line of code just as JS to iterate and display all images in React js. I would gladly appreciate your solution.

This is the full JS code:

    var images = [...document.querySelectorAll(".img")];
    var slider = document.querySelector(".slider");
    var sliderWidth;
    var imageWidth;
    var current = 0;
    var target = 0;
    var ease = 0.05;
    
   images.forEach((img, idx) => {
        img.style.backgroundImage = `url(./images/${idx + 1}.jpg)`;
      });
    
      function lerp(start, end, t) {
        return start * (1 - t) + end * t;
      }
    
      function setTransform(el, transform) {
        el.style.transform = transform;
      }
    
    
      function init() {
        sliderWidth = slider.getBoundingClientRect().width;
        imageWidth = sliderWidth / images.length;
        document.body.style.height = `${
          sliderWidth - (window.innerWidth - window.innerHeight)
        }px`;
      }
      window.addEventListener("resize", init);
    
      function animate() {
        current = parseFloat(lerp(current, target, ease)).toFixed(2);
        target = window.scrollY;
        setTransform(slider, `translateX(-${current}px)`);
        animateImages();
        requestAnimationFrame(animate);
      }
    
      function animateImages() {
        var ratio = current / imageWidth;
        var intersectionRatioValue;
    
        images.forEach((image, idx) => {
          intersectionRatioValue = ratio - idx * 0.7;
          setTransform(image, `translateX(${intersectionRatioValue * 70}px)`);
        });
      }
    
      init();
      animate();

How can I loop over the image folder and display all images using React js?

AgoraRTC can’t add multiple users in the webpage. can’t figure out what went wrong

i was trying to make a streaming website using Agora.io
in my JavaScript, i made a player template which will add to my webpage every time a new user enters. the client.on method should detect a new user coming & call back the function which should add the new user to the stream!

const APP_ID = "fe45f285661941ada5ef5d451fe8f626"
const CHANNEL = "main"
const TOKEN = "006fe45f285661941ada5ef5d451fe8f626IABxEPnj4KCl8i4+gcrg2F7Cc+nmjmOiRWq49ICnSOHfdGTNKL8AAAAAEACXVkQu42OcYgEAAQC9Y5xi"

const client = AgoraRTC.createClient({mode:"rtc",codec:"vp8"})

let localTracks = []
let remoteUsers = {}
let UID

let joinAndDisplayLocalStreams = async ()=> {

    client.on("user-published",handleUserJoined)

    UID = await client.join(APP_ID,CHANNEL,TOKEN,null)

    localTracks = await AgoraRTC.createMicrophoneAndCameraTracks()
    let player = ` <div class="video-container" id="user-container-${UID}">
                     <div class="name-wrapper"><span class="user-name">My name</span></div>
                         <div class="video-player" id="user-${UID}"></div>
                </div>`
    document.getElementById("video-streams").insertAdjacentHTML("beforeend",player)
    
    localTracks[1].play(`user-${UID}`)
    await client.publish([localTracks[0],localTracks[1]])
}

let handleUserJoined = async(user,mediaType)=>{
    remoteUsers[user.uid]= user
    await client.subscribe(user,mediaType)
    console.log(mediaType)

    if(mediaType==="video"){
        let player = document.getElementById(`user-container-${user.uid}`)
        if(player!=null){
            player.remove()
        }
        player = `<div class="video-container" id="user-container-${user.uid}">
                     <div class="name-wrapper"><span class="user-name">My name</span></div>
                         <div class="video-player" id="user-${user.uid}"></div>
                </div>`

        document.getElementById("video-streams").insertAdjacentElement("beforeend",player)
        user.videoTrack.play(`user-${user.uid}`)
    }
    if(mediaType==="audio"){
        user.audioTrack.play()
    }
}

joinAndDisplayLocalStreams()

I cannot change the display on a class in javascript

I’m trying to change visibility of an element in JavaScript.
I have tried using console and that told me the error was

Uncaught TypeError: Cannot read properties of null (reading ‘style’)
at openloginHud (index.js:20:40)
at HTMLInputElement.onclick (index.html:13:110)

My code

HTML:

<div class="login"><input id="login" type="submit" name="login" onclick="openloginHud();" value="Login"/></div>
<div class="loginHud">
        <div class="inputs">
            <h1>Login</h1>
            <div class="email"><input type="email" name="email" id="email" placeholder="Email"></div>
            <div class="password"><input type="password" name="password" id="pass" placeholder="Password"></div>
            <div class="submit"><input id="submit" type="submit" name="Login" onclick="login();" value="Login"/></div>
        </div>
    </div>

JavaScript:

function openloginHud() {
    document.getElementById("loginHud").style.display = "block";
}

Css:

.inputs {
    background-color: rgb(94, 94, 94);
    position: absolute;
    display: none;
    left: 50%;
    top: 40%;
    transform: translate(-50%, -50%);
    padding: 0 100px;
    padding-top: 50px;
    padding-bottom: 100px;
    border-radius: 55px;
}

.inputs .email {
    padding-bottom: 15px;
}

.inputs .email input,
.inputs .password input {
    padding: 10px;
    background: none;
    outline: none;
    border: 5px solid white;
    border-radius: 15px;
    color: white;
}

.inputs .email input::placeholder,
.inputs .password input::placeholder {
    color: rgb(199, 199, 199);
}

.inputs h1 {
    color: white;
    font-size: 65px;
    text-align: center;
}

.inputs .password input,
.inputs .email input {
    height: 20px;
    width: 250px;
}

Returning a value of a function into a function [duplicate]

I have a problem with returning my functions in js. Basicly Im calling a function in a js file and need to return something that is stored in chrome.storage extension, as seen in the script. This is very easy to achive as i thought, until it wasnt. This script i have doesnt work and returns undefined. Please help me, how do i return the correct thing?

Script:

function getSettings(){
    chrome.storage.sync.get(["grade", "gradeStyle", "finalColor"],(res)=>{
        return res
    })
}
export {getSettings};

How to extract number only after keyword in email without bold characters “*”

I am trying to only extract a confirmation number from string “Your confirmation number is 35657764. Please keep this number for future reference.”

I am using:

var emailKeywords = {
body: “Your confirmation number is”

var regExp;
regExp = new RegExp(“(?<=” + emailKeywords.body + “).*”);

I am getting back:

“* 35657764 *. Please”

-Thank you in advance.

TypeError: Cannot read properties of undefined (reading ‘getUser’)

Whats the problem in my code?

import { Request, Response } from "express"

import { ApiService } from “../services/apiService”;

class ApiController {

private apiService: ApiService

constructor() {
    this.apiService = new ApiService();
}

async createUser(request: Request, response: Response) {
    const {
        name, email, password
    } = request.body


    try {
        const apiService = new ApiService();
        const user =  await apiService.createUser(email, name, password)
        return response.json(user)
    } catch (error) {
        console.log(error)
    }
    
}

async getUser(request: Request, response: Response) {
    const {
        name,
    } = request.body

    try {
        // const apiService = new ApiService();
        const user = await this.apiService.getUser(name)

        return response.json(user)
    } catch (error) {
        console.log(error)
    }
    

    
}

}

export { ApiController }

enter image description here

How can I determine which checkbox is checked?

<table>
<tbody>
              <tr>  
                <th>Select</th>
                    <th>User Id</th>
                    <th>Id</th>
                    <th>Is Banned?</th>
                    <th>registration_date</th>
                
                </tr>
                {data.map((item, i) => (
                    <tr key={i}>
                        <td><input type="checkbox" checked={isChecked} /></td>
                        <td>{item.user_id}</td>
                        <td>{item.user_name}</td>
                        <td className="isbanned">{item.isbanned}</td>
                        <td>{item.registration_date}</td>
                    </tr>
                ))}
            </tbody></table>

enter image description here

this is my code as you see in up. My question is:

How can I detect user_id 1 checbox is checked?

How should I change my code? or what I can use for that?