the “canvas” method, where you put an image on an html canvas to get it as a blob and then convert it to webP (like how this package does it:
https://www.npmjs.com/package/webp-converter-browser)
doesn’t work with gifs- it just converts the first frame to a webp. Any figure out how to convert a gif to webp client side in js? am i gonna have to convert every frame to a webp and somehow combine it?
Category: javascript
Category Added in a WPeMatico Campaign
How do I remove my device from being linked to any previous administrator accounts using my phone number emails and personal information [closed]
I can’t find out how who or what administrator has authority over my device and my Google account but they have compromised my information and data.How do I report it
Factory reset called Motorola called straight talk and never can reach Google Cust service changed Google account but everytime I add my phone number to a new Google account they somehow get access to my password.
Custom cloud url issue
hii everyone i am facing a issue like i want to upload pdf file on the cloud storage but want the url to be in the format of my website domain name like if i’m using firebase cloud storage so instead of access url to be https://firebase.com/xyz it should be https://myorganisation.com/
can you please guide me over this i’m using node.js and mern stack for developing the file upload
I’ve seen this, The cloudinary is providing this functionality but it’s so expensive to afford.
Node app unable to retrieve API key from .env file
My node app seems to be able to grab from the API when the API key is hard coded into the file. When I attempt to use a .env to promote security,my browser is unable to grab that file.
[[[[[enter image description here](https://i.stack.imgur.com/xe4ip.png)](https://i.stack.imgur.com/fQYVr.png)](https://i.stack.imgur.com/pw3uv.png)](https://i.stack.imgur.com/GRdSf.png)](https://i.stack.imgur.com/mQlX5.png)
enter image description here
What I have tried:
Hard coding the API key to see if the issue lies with in the syntax
Directly moved the JS files within the html files to see if that fixes the issue
Added a moviesearch endpoint to see if that could resolve the problem
Adding an Access-Control-Allow-Origin header to Howler?
In this demo I’ve added a Access-Control-Allow-Origin header to Howler like this:
var sound = new Howl({
xhr: {
method: 'POST',
headers: {
Authorization: 'Access-Control-Allow-Origin:*',
},
withCredentials: true,
},
// autoplay: true,
loop: true,
volume: 1,
format: ['mp3'],
src: [mp3],
});
However the browser developer tooling still reports this error:
Access to XMLHttpRequest at 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3' from origin 'https://vitejsviterlhobl-tzl3-4abkv9qa--5173--c9a8a620.local-credentialless.webcontainer.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Any ideas on how to fix this?
Unable to create a RegEx in JavaScript that matches any character except the one in the list
I am trying to create a conditions that password shouldn’t contain any characters except letters (both upper case and lower case), digits and characters in this list !@#$%^&*
I am using the carrot character to match anything except but nothing is working
For example I am trying to get a match using this code
const paragraph = arguments.Value;
const regex = /[^a-zA-Zd!@#$%^&*]+$/g;
const found = paragraph.match(regex);
console.log(arguments.Value);
console.log(found);
But found is ALWAYS null no matter what
Also when I use this syntax
arguments.IsValid = /^[^a-zA-Zd!@#$%^&*]$/.test(arguments.Value);
The result us NEVER valid when I try to use the carrot ^ (except for symbol)
Should be something very simple, can some one suggest what I am doing wrong?
Thank you in advance
Is it advisable to determine login status using localStorage in Angular AuthGuard?
In my Angular application, I’m currently developing an authentication guard (AuthGuard) to control access to certain routes based on the user’s login status. I’m considering using the localStorage to store the authentication token and checking its presence and validity within the AuthGuard to determine if the user is logged in. Here’s a simplified version of how I plan to implement it:
import { JwtHelperService } from '@auth0/angular-jwt';
export const routeguardGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const helper = new JwtHelperService();
const isExpired = helper.isTokenExpired(localStorage.getItem('token'));
const router: Router = inject(Router);
if (isExpired == false && localStorage.getItem('token') != "" && localStorage.getItem('token') != null) {
return true;
} else {
router.navigate(['/AdminLogin']);
return false;
}
};
My question is, is this approach considered a good practice for determining the login status in this way? Are there any potential drawbacks, security risks, or performance issues associated with relying on localStorage for this purpose? Additionally, are there alternative approaches or best practices recommended for managing user authentication within Angular applications?
I want to ensure that my authentication logic adheres to industry standards and provides a secure and efficient user experience. Any insights or recommendations would be highly appreciated.
Thank you for your valuable input!
How can I remove a class without triggering a CSS animation?
I’m trying to create a website in which there are some simple CSS animations:
fade-in: Causes the element to fade into view, anderror: Causes the element to turn red and shake for a brief moment.
When I trigger the error animation through JS, once it’s done, the fade-in animation plays as well, which is not desired. Here’s the CSS and JS:
style.css:
...
/* All children of the `splash` class are subject to the `fade-in` animation */
.splash * {
animation: fade-in 1s ease-in;
opacity: 1;
}
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.error {
animation: shake 0.4s ease-in-out;
border-color: red;
}
@keyframes shake {
0% { transform: translateX(0); }
25% { transform: translateX(-5px); }
50% { transform: translateX(5px); }
75% { transform: translateX(-5px); }
100% { transform: translateX(0px); }
}
.no_transition {
animation: none;
transition: none;
}
...
script.js:
...
function err(elem, msg) {
if (msg) alert(msg);
// start the transition
elem.classList.add('error');
elem.disabled = true;
setTimeout(() => {
// 1 second later, remove the `error` class.
elem.classList.add('no_transition');
elem.classList.remove('error');
elem.disabled = false;
elem.classList.remove('no_transition'); // this is what triggers the `fade-in` animation again
}, 1000);
}
...
Since adding / removing a class will trigger the CSS animation, I tried creating a separate class (no-transition) that blocks all animations and transitions. However, once I remove it, fade-in triggers once again.
Is there a way to work around this, and add / remove these CSS classes without triggering the fade-in animation?
Javascript: how do I get the value of an input in real time?
I am programming a web page and I have an input where the user must enter a 5-letter word and a button that will use said word for a function, I want the button to be disabled as long as 5 letters have not been entered but I don’t know how to do it exactly, so I was thinking that if I could get the value of the input in real time I could try something.
I haven’t tried anything yet because I don’t know where to start. I know how to disable a button, I just don’t know how to get the input value in real time.
How to access property from db json to fetch in chatbox
I have created Student management system, with form fields etc.
That data will stored in db.json file, and I have model.ts of my object interface.
I have chatbot component, when I ask chat what was the emergency contact of Ramya? Then it should give response to get data from dbjson it should give response
But here I don’t know why I have tried much I’m able to crack the issue, how to fetch data based on asking questions.
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../shared/api.service';
import { studentdata } from '../student.model';
interface Message {
content:string;
type: 'incoming' 'outgoing';
}
@Component({
selector: 'app-chatbox',
templateUrl: './chatbox.component.html',
})
styleUrls: ['./chatbox.component.css']
export class ChatboxComponent implements OnInit {
constructor(private apiservice: ApiService) { }
ngOnInit(): void {
}
showTypeindicator: boolean=false;
showChatbot: boolean = false;
userMessage: string ="";
messages: Message[]=[];
toggleChatbot(){
this.showChatbot=!this.showChatbot;
if(!this.showChatbot){
this.userMessage="";
}}
handleChat(event?: Event) {
if (event && event.type==='keydown' && (event as KeyboardEvent).key!=='Enter') { return;
}
const message=(this.userMessage ??'').trim();
if(!message) return;
this.messages.push({
content:message,
type: 'outgoing'
});
this.userMessage='';
this.showTypeindicator=true;
// messages: Message[]=[];
setTimeout(async() => {
const response = await this.generateResponse(message);
this.showTypeindicator=false;
this.messages.push({
content: await response,
type: 'incoming'
});
}, 2000);
}
getRandomResponse(): string{
const responses=[
"Sure, I can help with that.",
"Let me find the information for you.",
"Here's what I found",
"Ooops! i'm still learning, Can you try asking differently?", "i'm sorry, i couldn't understand that."
];
const randomIndex=Math.floor(Math.random()*responses.length);
return responses [randomIndex];
}
private async generateResponse(message: string): Promise <string>
{
const lowercaseMessage = message.toLowerCase();
if(lowercaseMessage.includes('date of birth')|| lowercaseMessage.includes('dob'))
{
return await this.getPropertyFromStudent(message, 'dob');
} else if (lowercaseMessage.includes('emergency contact'))
{ return await this.getPropertyFromStudent(message, 'emergencyContact');
}
else if (lowercaseMessage.includes('city'))
{
return await this.getPropertyFromStudent(message, 'city');
}
else if
(lowercaseMessage.includes('bloodType')
{
return await this.getPropertyFromStudent(message, 'bloodType');
}
else if(lowercaseMessage.includes('address'))
{
return await this.getPropertyFromStudent(message, 'address');
} else if (lowercaseMessage.includes('guardian name'))
{
return await this.getPropertyFromStudent(message, 'guardianName');
}
else if (lowercaseMessage.includes('guardian contact number'))
{
return await this.getPropertyFromStudent(message, 'guardianContact');
}
else if (lowercaseMessage.includes('list of how many students'))
{ return await this.getAllDetailsOfStudent(message);
}
else{
return this.getRandomResponse();
}
}
private async getPropertyFromStudent(message: string, property: string): Promise <string>
{
const studentName=this.extractStudentName(message); console.log("extracted student:", studentName)
try{
const studentData: studentdata=await this.apiservice.getstudent (studentName).toPromise(); console.log('student data:', studentData)
const property Value=studentData [property];
console.log("retrieved ${property) for ${studentName}:", propertyValue); return propertyValue || 'Sorry, could not find${property for ${studentName}.';
}
catch(error) {
console.error('Error fetching student details: ', error) return 'Sorry, something went wrong while fetching student details.';
}
private extractStudentName (message: string):string
- const parts message.split('of');
if(parts.length<2){
return '';
}
const studentName=parts[1].trim();
console.log("extracted:", studentName) return studentName
}
private async getListOfStudentCount(): Promise<string>
{
try{
const students: studentdata[] = await this.apiservice.getstudent().taPromise(); return 'Total number of students: ${students.length}';
}
catch(error)
{
return 'sorry, something went wrong while fetching student details.";
}
}
private async getAllDetailsOfStudent(message: string): Promise <string>
{
const studentName = this.extractStudentName(message);
try
{
}
const studentData: any await this.apiservice.getstudent (studentName).toPromise(); return JSON.stringify(studentData, null, 2);
catch(error)
{
return 'Sorry, something went wrong while fetching student details.';
}
}
}
Service file .ts
import { HttpClient } from '@angular/common/http'; import { ReturnStatement } from '@angular/compiler'; import { Injectable } from '@angular/core'; import { map } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private_http: HttpClient) {}
poststudent(data:any){
return this._http.post<any>("http://localhost:3000/posts", data)
.pipe (map((res: any)=>{
return res;
}))
}
getstudent(name?:string){
console.log("fetchin student data:", name);
if(name) {
return this._http.get<any>('http://localhost:3000/posts/${name})
.pipe (map((res: any)=>{
return res;
}))
else{
return this._http.get<any>("http://localhost:3000/posts") pipe(map((res: any)=>{ return res;
}))
}
}
updatestudent(data: any, id: number) {
return this._http.put("http://localhost:3000/posts"+id, data) .pipe(map((res:any)=>{
return res;
}))
}
Student.model.ts:
export class studentdata{
id:number=0;
name:string="
email:string=";
mobile:string=";
city:string=";
address:string=";
dob:string=";
gender:string=";
guardianName:string=";
guardianContact:string=";
emergencyContact:string=";
nationality:string=";
blood Type:string=";
}
db.json file:
{
"posts": [
{
"id": 1,
"name": "Ramya",
"email": "[email protected]",
"mobile": 56637373,
"city": "chennai",
"address": "",
"dob": "2024-03-21",
"gender": "female",
"guardianName": "maoj",
"guardianContact": "466463636",
"emergency Contact": "76477784262",
"nationality": "India",
"bloodType": "o positive"
}
],
"comments":[],
"profile": (
"name": "typicode"
}
Cross-origin request not setting cookies, reactJs, Django Backend, Firefox + Chrome
I have a react app, and sending requests as such:
const public_key_r = await axios.get(
"https://eliptum.tech/get-public-key",
{
withCredentials: true, // This is crucial for cookies to be sent and received in cross-origin requests
},
);
const publicKey = public_key_r.data.publicKey;
const csrfToken = public_key_r.data.csrf_token;
console.log(csrfToken);
const encryptedPassword = await encryptData(password, publicKey, false);
const response = await axios.post(
"https://eliptum.tech/user/create",
{
username,
encryptedPassword,
email,
phone_number: phoneNumber,
},
{
withCredentials: true,
headers: {
"X-CSRFToken": csrfToken,
},
},
);
My Backed view for https://eliptum.tech/get-public-key get request is:
class PublicKeyView(View):
def get(self, request):
# Ensure a session ID is available
if not request.session.session_key:
request.session.save()
session_id = request.session.session_key
private_key, public_key = RSAKeyManager.get_keys(session_id)
if not private_key or not public_key:
# Keys are generated as bytes, so decode them before storing
private_key, public_key = RSAKeyManager.generate_keys()
RSAKeyManager.store_keys(session_id, private_key.decode('utf-8'), public_key.decode('utf-8'))
if isinstance(public_key, bytes):
public_key = public_key.decode('utf-8')
# Retrieve CSRF token
csrf_token = get_token(request)
# Construct the JSON response
response_data = {
"session_id": session_id,
"public_key": public_key,
"csrf_token": csrf_token
}
# Create JsonResponse with the response data
response = JsonResponse(response_data, status=200)
# Set CSRF token as a cookie in the response
# Ensure the Secure and SameSite attributes are correctly set for cross-origin compatibility
response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None')
response['Access-Control-Allow-Credentials'] = 'true'
return response
Settings are:
"""
Django settings for django_backend project.
Generated by 'django-admin startproject' using Django 5.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
from utils.utils import get_secrets
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-&sru-aw9zw@2t*hyy7eh&ynb5buu(tw_sd7=xsgt(+6bi5&h4f"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"backend_app",
"corsheaders",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "django_backend.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "django_backend.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'eliptumr_users',
'USER': 'eliptumr_db',
'PASSWORD': get_secrets("DB_PASSWORD"),
'HOST': 'servercp73.20x.host',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
SANDBOX = "https://7w37f9-3000.csb.app"
AUTH_USER_MODEL = 'backend_app.CustomUser'
INPUT_DATA_ENCRYPT = False
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
'https://eliptum.tech',
SANDBOX,
]
ALLOWED_HOSTS = ['eliptum.tech', SANDBOX]
CSRF_TRUSTED_ORIGINS = ['https://eliptum.tech', SANDBOX]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['https://eliptum.tech', SANDBOX]
Added everything i could find to make cross origin work but, no, for:
const response = await axios.post( "https://eliptum.tech/user/create"
Backend has django-cors-headers and response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None') response['Access-Control-Allow-Credentials'] = 'true'
All requests have withCredentials: true for axios, not sure what’s missing or what’s not configured properly, if anything
Basically i have my backed at eliptum.tech host, and frontend on some sandbox, but there is no way for me to make em work together it seems
Not sure if you can access https://7w37f9-3000.csb.app/#, its the frontend that you could test what im saying, gotta select signin/signup and then signup with a random account
Issue is i cannot do the post request because:
Reason given for failure:
CSRF cookie not set.
Which is fair considering no cookies are set 🙁
ReactJs how to convert svg element into an .eps file?
I can’t find a suitable library that can convert svg element on the page to .eps file. I tried various options that chatgpt offers, but this creates an not valid eps file. How to do this correctly? I tried such code, Photoshop and Adobe Illustrator do not open this file, but online eps viewer fviewer.com/view-eps opens it. Maybe there are some other ideas?
const dataURItoBlob = (dataURI) => {
const byteString = atob(dataURI.split(",")[1]);
const mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
};
const svgElement = svgRef.current;
const svgXml = new XMLSerializer().serializeToString(svgElement);
const canvas = document.createElement("canvas");
canvas.width = svgElement.clientWidth;
canvas.height = svgElement.clientHeight;
const ctx = canvas.getContext("2d");
const svgBlob = new Blob([svgXml], { type: "image/svg+xml" });
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0);
const epsDataUri = canvas.toDataURL("image/eps", 1.0);
const blob = dataURItoBlob(epsDataUri);
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "image.eps";
a.click();
window.URL.revokeObjectURL(a.href);
};
img.src = URL.createObjectURL(svgBlob);
How to move stacked bar chart label position only for bars plotting in negative direction with Google Charts API in ASP.NET JavaScript
I am creating a stacked bar chart comparing quarterly results of two different years. One year is plotted as a positive value bar chart and the second year is plotted using the result value * -1 so it plots below the same quarter.
In this example, 2023 Qtr 1 is 469 and 2022 Qtr 1 is really 676. The bottom year values are multiplied by -1 during a query.
How do I make the negative value display below the bottom bar and keep the positive value on top as it is now?
JavaScript:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var jsonList = @(Json.Serialize(Model.listAllAircraftChartQuarterly))
var title = 'Quarterly Aircraft Transaction Trend';
data.addColumn('string', 'Quarter');
data.addColumn('number', '2023');
data.addColumn('number', '2022');
data.addColumn('number', '% Change');
data.addRows(jsonList.map((p) => {
return [p.yearQuarter, p.year2top, p.year3bottom, p.year2percent];
}));
var formatPercent = new google.visualization.NumberFormat({ pattern: '#.#%' });
formatPercent.format(data, 3);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3,
{
calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation"
}
]);
var options = {
title: title,
titlePosition: 'out',
isStacked: true,
seriesType: "bars",
vAxes: {
0: {
textPosition: 'out',
viewWindowMode: 'pretty',
title: "",
viewWindow: { min: -1100, max: 1100 },
gridlines: { color: 'lightgray' },
},
1: {
textPosition: 'out',
viewWindow: { min: -1, max: 1 },
format: 'percent',
gridlines: { color: 'transparent' }
},
},
series: {
0: { targetAxisIndex: 0, color: 'blue' },
1: { targetAxisIndex: 0, color: 'gray' },
2: { targetAxisIndex: 1, color: 'red', type: 'line', lineWidth: 1, lineDashStyle: [4, 4], pointSize: 5 },
},
width: '100%',
height: '300',
legend: { position: 'top' },
chartArea: {
height: '100%',
width: '100%',
top: 48,
left: 60,
right: 60,
bottom: 75
},
annotations: {
highContrast: false,
textStyle: {
color: 'red',
fontSize: 12,
bold: true
},
alwaysOutside: true
},
}
var chart = new google.visualization.ComboChart(document.getElementById('primaryYear2and3'));
chart.draw(view, options);
document.getElementById('downloadimg2and3').innerHTML = '<a download="google-chart-image" href="' + chart.getImageURI() +
'"><button type="button" class="btn btn-outline-dark btn-sm opacity-25 ms-4 mb-3">Download Chart Image</button></a>';
window.addEventListener('resize', drawChart, false);
}
</script>
I have tried researching other posts.
Get user input value info when i render the html doc using iframe in react
I have an input tag in html doc that I get from API.
<input placeholder="Enter Name" type="text"/>
And I am rendering this in react in .js component with iframe srcDoc,
When user enters anything on the input field then i want to capture that info in react component but i am not sure how i can capture input value that is part of html doc which i am rendering using iframe.
Can someone please help with this or any suggestions ?
Why do my buttons only work sometimes when i repeatedly press them? [closed]
Everything worked fine until I added custom font and the program became slow. I removed the custom font after and noticed the buttons are not working as they usually did (the event handler usually ran the code as soon as i clocked a button.)
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock, Paper, Scissors</title>
<link rel="stylesheet" href="index.css">
<script src="index.js" defer></script>
</head>
<body background="ImagesBG.png">
<div id="title">
<h1 class="head">ROCK PAPER SCISSORS</h1>
<h4 class="head">The first to 5 points win</h4>
</div>
<div id="gameContainer">
<div class ="playersContainer">
<img class="icon" src="ImagesUser.jpg" alt="user Image">
<ul id="buttonList" class="buttonList">
<li><button id="rock"><img class="btnImg" src="ImagesRock.png" alt="Rock"></button></li>
<li><button id="paper"><img class="btnImg" src="ImagesPaper.png" alt="Paper"></button></li>
<li><button id="scissors"><img class="btnImg" src="ImagesScissors.png" alt="Scissors"></button></li>
</ul>
</div>
<div id="swords">
<img src="Images/Swords.png" alt="Crossing swords">
<h6 id="gameInfo"></h6>
</div>
<div class ="playersContainer">
<img class="icon" src="ImagesComputer.png" alt="computer Image">
<ul class="buttonList">
<li><button ><img class="btnImg" src="ImagesRock.png" alt="Rock"></button></li>
<li><button ><img class="btnImg" src="ImagesPaper.png" alt="Paper"></button></li>
<li><button ><img class="btnImg" src="ImagesScissors.png" alt="Scissors"></button></li>
</ul>
</div>
</div>
<div>Icons made from <a href="https://www.onlinewebfonts.com/icon">svg icons</a>is licensed by CC BY 4.0</div>
</body>
</html>
And here is my javascript code
let cScore = 0;
let pScore = 0;
let userSelection = document.querySelector('#buttonList');
userSelection.addEventListener('click', (event) =>
{
let target = event.target;
switch (target.id)
{
case "rock":
// playerChoice = "rock";
console.log("Player throws rock");
playGame("rock");
break;
case "paper":
// playerChoice = "paper";
console.log("Player throws paper");
playGame("paper");
break;
case "scissors":
// playerChoice = "scissors";
console.log("Player throws scissors");
playGame("scissors");
break;
}
});
function getComputerChoice()
{
let compChoice = Math.floor(Math.random() * 3 + 1);
if (compChoice === 1)
{
compChoice = "rock";
console.log("Computer throws rock");
}
else if (compChoice === 2)
{
compChoice = "paper";
console.log("Computer throws paper");
}
else
{
compChoice = "scissors";
console.log("Computer throws scissors");
}
return compChoice;
}
function playGame(playerChoice)
{
const playerSelection = playerChoice;
const computerSelection = getComputerChoice();
console.log(playRound(playerSelection, computerSelection));
winner = playRound(playerSelection, computerSelection);
if (winner === "Player wins round!")
{
pScore += 1;
}
if (winner === "Computer wins round!")
{
cScore += 1;
}
console.log("Player: " + pScore);
console.log("Computer: " + cScore);
if (cScore == 5)
{
endGame("computer");
}
if (pScore == 5)
{
endGame("player");
}
if (pScore == 5 && cScore == 5)
{
endGame("tie");
}
}
function playRound(playerSelection, computerSelection)
{
//Round is a tie
if ((playerSelection === "rock" && computerSelection === "rock") ||
(playerSelection === "paper" && computerSelection === "paper") ||
(playerSelection === "scissors" && computerSelection === "scissors"))
{
document.querySelector('#gameInfo').innerHTML = "Round is a tie!";
return "Round is a tie";
}
//Player wins round
if ((playerSelection === "paper" && computerSelection === "rock") ||
(playerSelection === "scissors" && computerSelection === "paper") ||
(playerSelection === "rock" && computerSelection === "scissors"))
{
document.querySelector('#gameInfo').innerHTML = "Player wins round!";
return "Player wins round!";
}
//Computer wins round
if ((playerSelection === "scissors" && computerSelection === "rock") ||
(playerSelection === "rock" && computerSelection === "paper") ||
(playerSelection === "paper" && computerSelection === "scissors"))
{
document.querySelector('#gameInfo').innerHTML = "Computer wins round!";
return "Computer wins round!";
}
}
function endGame(gameWinner)
{
switch (gameWinner) {
case "player":
break;
case "computer":
break;
case "tie":
break;
}
}
I don’t know if the problem is with the event handler in the JS file or in the HTTML body.
