How can I add when someone adds my bot to their server the bot will send a message on my support server the info of that server is joined.
Like an embed:
title: Bot joined a new server
description: guild name, guild id, guild invite link or server invite link
Category: javascript
Category Added in a WPeMatico Campaign
How do I change the location of the pushed array items by clicking on a day item with Vue3?
Here’s my calendar row with day items in it:
The problem is…
…when I select another day, let’s say 13th of Monday, and after that try to add new tasks they still push to the task array of the first day.
Let me just show you:
On the Image above I switch to Monday, and the task list is empty as it should be by default, looks pretty good to me….but…
After I try to add new tasks, it didn’t add any to the selected day, but just pushed them into the first one (I added two more, there were 3 on the first screen)
Let me show you the code:
This is my main component in which all other’s are used in:
Main.vue
setup() {
// Create days:
const currDay = ref({});
const dayArr = ref([]);
// Just a library for working with dates:
const moment = require("moment");
const daysRemainingThisMonth = moment()
.endOf("month")
.diff(moment(), "days");
/*=============================================
= Firebase =
=============================================*/
const { user } = useAuthState();
const auth = getAuth();
const router = useRouter();
const signOutUser = async () => {
try {
await signOut(auth);
router.push("/auth");
} catch (e) {
alert(e.message);
}
};
/*===== End of Firebase ======*/
const store = useStore();
// Generate the day data:
const fillDayArray = () => {
dayArr.value = Array(daysRemainingThisMonth)
.fill("")
.map((item, index) => {
return {
currDay: moment().add(index, "day").format("D"),
dayOfWeek: moment().add(index, "day").format("dddd"),
tasks: [ ],
id: Math.floor(Math.random() * new Date()),
};
});
currDay.value = dayArr.value[0];
};
const updateCurrDay = (value) => {
currDay.value = value;
};
onMounted(() => {
fillDayArray();
});
Template of Main.vue:
<template>
<div id="main">
<!-- ! Top Level: -->
<div class="auth"></div>
<div class="greeting-block">
<button @click="signOutUser">Sign Out</button>
<h1 id="greet-user">{{ user?.email }}</h1>
</div>
<div class="header-container">
<Header />
<Menu />
</div>
<div class="calendar-display">
<Calendar
:dayArr="dayArr"
@updateCurrDay="updateCurrDay"
/>
</div>
<div class="task-list">
<TaskView
v-if="dayArr.length"
:dayArr="dayArr"
:currDay="currDay"
/>
</div>
</div>
</template>
Component where the tasks are rendered: TaskView.vue
props: {
dayArr: {
type: Array,
default: () => [],
},
currDay: {
type: Object,
default: () => ({}),
},
},
setup(props) {
const store = useStore();
const dayArrData = ref(props.dayArr);
const currDay = ref(props.currDay);
const getClickedTask = (item) => {
store.state.clickedTask = item;
store.state.cardStatus
? (store.state.cardStatus = false)
: (store.state.cardStatus = true);
};
// ! Delete Item:
const deleteItem = (idx) => {
currDay.value.tasks.splice(idx, 1);
};
// ====== How do I tell it to push items to the currDay? ======
const addItem = () => {
currDay.value.tasks.push({
name: "Empty Task" + Math.random().toString().substring(0, 4),
description: "No description...",
});
};
console.log(currDay.value);
onMounted(() => {});
return {
getClickedTask,
deleteItem,
addItem,
dayArrData,
};
},
Template of TaskView.vue:
<template>
<div>Active card: {{ currDay }}</div>
<hr />
<div>Current Task is: {{ currDay.dayOfWeek }}</div>
<div class="task-wrapper">
<p id="task-counter">Tasks Today: {{ currDay.tasks.length }}</p>
<div class="task-counter-wrapper">
<!-- ? Render if there are no tasks available: -->
<div class="empty-msg" v-if="currDay.tasks.length == 0">
<p>Start by adding a New Task!</p>
</div>
<div class="task-list" v-for="(task, idx) in currDay.tasks" :key="idx">
<div class="list-item">
<div class="container">
<input class="list-checkbox" type="checkbox" />
{{ task.name }}
</div>
<div class="item-actions">
<button class="edit-item btn" @click="getClickedTask(task)">
<img class="icon" src="./Images/editing.png" />
</button>
<button class="delete-item btn" @click="deleteItem(idx)">
<img class="icon" src="./Images/delete.png" />
</button>
</div>
</div>
</div>
</div>
<div class="item-card">
<ItemCard />
</div>
<div class="add-task-wrapper">
<button id="add-task-btn" @click="addItem()">+ Add a new task</button>
</div>
</div>
</template>
Call object function in RequireJS
I use RequireJS to load some scripts.
Now I would like to create some own methods which also needs the loaded script. I’ve tried a lot but I always get Uncaught (in promise) ReferenceError: hd is not defined
Calling the method ‘connect’:
hd.connect.call(token);
JS
...
require.config({
shim: {
'socket.io': {
exports: 'io'
},
'socket.io-stream': {
exports: 'ss'
}
},
paths: {
'socket.io': WEBSOCKET_PROXY_HOST + '/socket.io/socket.io',
'socket.io-stream': WEBSOCKET_PROXY_HOST + '/socket.io-stream/socket.io-stream'
},
waitSeconds: 1
});
requirejs([
'socket.io', 'socket.io-stream'
], function(io, ss) {
// Setup Methods & Events
const hd = {
connect : function(token) {
// Connect to Socket, Proxy Server & authenticate
socket = io(WEBSOCKET_PROXY_HOST, {
auth: {
token: token
}
}).on('connect', function(data) {
socketConnected = true;
isStreaming = false;
console.log('connected to socket');
if (activeRecording) {
//#startRecording();
}
});
...
Is there a way to import an object from another javascript script
I have a JavaScript object which I want to work with on another JavaScript script, is there a way to import it? So far I’ve tried this code:
import { object } from './mainscript.js';
And it doesn’t work.
accessing passed data on front end
I have this on the node.js
backend:
var getschedule = "select * from SCHEDULE"
console.log(getschedule);
ibmdb.open(ibmdbconn, function(err, conn) {
if (err) return console.log(err);
conn.query(getschedule, function(err, rows) {
if (err) {
console.log(err);
}
console.log(rows)
res.render("calendar.ejs", {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname});
conn.close(function() {
});
});
});
and as you can see I am passing data: rows
. Now in my <script>
on the front end, i want to access all the data inside data
, which i am passing. how can i do this?
Mocking Controller dependency in Nestjs
I am trying to mock my controller using nestjs createTestingModule and I have added overrider provider to mock the service but it still giving me this error(Screenshot attached screenshot). Kindly help.
I also tried added the other dependencies too but the error is same
Here is my controller.ts file
import {Body, NotFoundException, OnModuleInit, Param, Patch} from "@nestjs/common";
import {BitvavoService} from "./bitvavo.service";
import {DeleteMethod, GetMethod, PostMethod, PatchMethod} from "../../../../global/operations";
import {ApiController} from "../../../../utils/endpoints/api-controller.decorator";
import bitvavo, {BitvavoOrderResponse} from "bitvavo";
import {Repository} from "../../../repository/repository";
import {BitvavoTarget} from "./bitvavo-target";
import {RepositoryFactory} from "../../../repository/repository-factory.service";
import {CollectionNames} from "../../../repository/collection-names";
import {ProducerTargetBindingService} from "../../producer-target-binding/producer-target-binding.service";
import {User, UserClass} from "../../../../utils/endpoints/user.decorator";
import {Permissions} from "../../../../utils/endpoints/permissions.decorator";
import {Permission} from "../../../../utils/permission.enum";
import {EncryptionService} from "../../../encrypt/encrypt.service";
import {
BitvavoBalanceDto,
BitvavoPlaceOrderDto,
BitvavoSingleTargetResponse,
CreateBitvavoTargetDto,
UpdateBitvavoTargetDto,
ChangeBitvavoTargetMode,
SellSingleBot
} from "./bitvavo-dtos";
import {toTargetDto} from "../target-dto";
import {ApiBotService} from "../../signal-producers/implementers/api-bot/api-bot.service";
const getBalances = async function (target: BitvavoTarget, decryptedKey: string, decryptedSecret: string) {
try {
const client = createBitvavoClient(decryptedKey, decryptedSecret);
return (await client.balance({})).map(balanceToDto);
} catch (e) {
return null;
}
};
@ApiController("signal-targets/bitvavo")
export class BitvavoController implements OnModuleInit {
private repository: Repository<BitvavoTarget>;
async onModuleInit() {
this.repository = await this.repositoryFactory.create(BitvavoTarget);
}
constructor(
private bitvavoService: BitvavoService,
private repositoryFactory: RepositoryFactory,
private producerTargetBindingService: ProducerTargetBindingService,
private encryptionService: EncryptionService,
private apiBotService: ApiBotService
) {}
@PostMethod()
@Permissions(Permission.CreateTargets)
async create(@Body() targetDto: CreateBitvavoTargetDto, @User() user: UserClass) {
const userTargets = await this.repository.getAll(user.sub);
const safeModel = {
...targetDto,
name: targetDto.name ? targetDto.name : `Bitvavo Wallet ${userTargets.length + 1}`,
key: this.encryptionService.encrypt(targetDto.key),
secret: this.encryptionService.encrypt(targetDto.secret)
};
await this.repository.create({...safeModel, userId: user.sub, positions: []}); // TODO some unique checking stuff
}
@GetMethod()
@Permissions(Permission.ReadTargets)
async get(@User() user: UserClass) {
if (user.permissions.includes(Permission.AdminTargets)) {
return await this.repository.getAllInternal();
}
return await this.repository.getAll(user.sub);
}
@GetMethod("/:id")
@Permissions(Permission.ReadTargets)
async getOne(@Param("id") targetId: string, @User() user: UserClass): Promise<BitvavoSingleTargetResponse> {
let targetOpt;
if (user.permissions.includes(Permission.AdminTargets)) {
targetOpt = await this.bitvavoService.getOneInternal(targetId);
} else {
targetOpt = await this.bitvavoService.getOne(targetId, user.sub);
}
if (!targetOpt) {
throw new NotFoundException();
}
const {bindings, target} = targetOpt;
const decryptedKey = this.encryptionService.decrypt(target.key);
const decryptedSecret = this.encryptionService.decrypt(target.secret);
const balances = await getBalances(target, decryptedKey, decryptedSecret);
return {
target: toTargetDto({type: CollectionNames.Bitvavo, name: target.name, _id: target._id, targetMode: target.targetMode}),
// producer: mapProducerToDto(producer),
balances: balances,
bindings: bindings
};
}
@PostMethod("/:id/placeOrder")
async placeOrder(@Param("id") id: string, @Body() body: BitvavoPlaceOrderDto, @User() user: UserClass): Promise<BitvavoOrderResponse> {
let target;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneByIdInternal(id);
} else {
target = await this.repository.getOneById(id, user.sub);
}
if (!target) {
throw new NotFoundException();
}
return await this.bitvavoService.handleSignal(target, body);
}
@Patch("/:id")
@Permissions(Permission.EditTargets)
async update(@Param("id") id: string, @User() user: UserClass, @Body() targetDto: UpdateBitvavoTargetDto) {
let target;
let key;
let secret;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneModelByIdInternal(id);
} else {
target = await this.repository.getOneModelById(id, user.sub);
}
if (!target) {
throw new NotFoundException();
}
if (targetDto.key) {
key = this.encryptionService.encrypt(targetDto.key);
} else {
key = target.key;
}
if (targetDto.secret) {
secret = this.encryptionService.encrypt(targetDto.secret);
} else {
secret = target.secret;
}
Object.assign(target, {...targetDto, key, secret});
await target.save();
}
@DeleteMethod("/:id")
@Permissions(Permission.DeleteTargets)
async deleteTarget(@Param("id") id: string, @User() user: UserClass) {
let target;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneModelByIdInternal(id);
} else {
target = await this.repository.getOneModelById(id, user.sub);
}
if (!target) {
throw new NotFoundException();
}
await this.repository.deleteById(id);
await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
}
@PostMethod("/:id/sellto/:base")
@Permissions(Permission.EditTargets)
async sellAllForTarget(@Param("id") id: string, @Param("base") base: string, @User() user: UserClass) {
let target;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneModelByIdInternal(id);
} else {
target = await this.repository.getOneModelById(id, user.sub);
}
if (!target) {
throw new NotFoundException();
}
await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
await this.bitvavoService.sellAllToAsset(target, base);
}
@PatchMethod("/:id/changeTargetMode")
@Permissions(Permission.EditTargets)
async changeTargetMode(@Param("id") id: string, @Body() targetDto: ChangeBitvavoTargetMode, @User() user: UserClass) {
let target;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneModelByIdInternal(id);
} else {
target = await this.repository.getOneModelById(id, user.sub);
}
if (!target) {
throw new NotFoundException();
}
Object.assign(target, {...target, targetMode: targetDto.targetMode});
await target.save();
}
@PostMethod("/:id/stopBot/:base")
@Permissions(Permission.EditTargets)
async sellSingleTarget(@Param("id") id: string, @Param("base") base: string, @Body() body: SellSingleBot, @User() user: UserClass) {
let target;
let producer;
if (user.permissions.includes(Permission.AdminTargets)) {
target = await this.repository.getOneModelByIdInternal(id);
} else {
target = await this.repository.getOneModelById(id, user.sub);
}
producer = await this.apiBotService.getOneModelInternal(body.botName);
if (!target || !producer) {
throw new NotFoundException();
}
await this.producerTargetBindingService.deleteSingleForTarget(
{id: target.id, type: CollectionNames.Bitvavo},
{id: producer._id, type: CollectionNames.ApiBot}
);
await this.bitvavoService.sellAllToAsset(target, base);
}
}
export const createBitvavoClient = (key: string, secret: string) => {
return bitvavo().options({
APIKEY: key,
APISECRET: secret,
ACCESSWINDOW: 10000,
RESTURL: "https://api.bitvavo.com/v2",
WSURL: "wss://ws.bitvavo.com/v2/",
DEBUGGING: false
});
};
const balanceToDto = (balance: {symbol: string; available: string; inOrder: string}): BitvavoBalanceDto => {
return balance as BitvavoBalanceDto;
};
Here is my controller.spec.ts
import {BitvavoService} from "./bitvavo.service";
import {Test} from "@nestjs/testing";
import {BitvavoController} from "./bitvavo.controller";
describe("Bitvavo Controller", () => {
let controller: BitvavoController;
const mockValue = {};
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [BitvavoController],
providers: [BitvavoService]
})
.overrideProvider(BitvavoService)
.useValue({onModuleInit: jest.fn(), handleSignal: jest.fn(), sellAllToAsset: jest.fn(), getOne: jest.fn(), getOneInternal: jest.fn()})
.compile();
});
it("test", () => {});
});
Get current user level without using while loops?
In my messaging app, I have a level system that track’s a user’s activeness with XP. It doesn’t store the actual level, only the amount of XP they have. Here’s the function for calculating the level:
function calculateLevel(num) {
var lv = 0;
do {
lv++;
} while (num >= Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))));
var x = num-Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1))));
var left = Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv))))-num;
var thislv = x + left;
return {
level: lv,
xp: x,
left: left,
next: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))),
prev: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1)))),
thislv: thislv+1
};
}
The formula for calculating how much XP each level requires is 30√(√(level)). However, I don’t want to use a while loop, because the app starts to slow down a bit after level 60. Is there a way to get the current level without having to use loops?
delete an object in an array based on index at level 1 and level 2
I have a array of object which has sub arrays, I want to delete the subarray object based on the index from both the levels.
For example if want to delete object with id:12 I should pass firstIndex = 0 and secondIndex = 1;
Pls note above mentioned eg: is for better understanding of question and not to delete element by id should be deleted based on index only(use case is different and index are received from different source).
const array = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 12, value: y},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
{id: 23, value: c},
],
}
]
firstIndex = 1, secondIndex = 2
const result = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 12, value: y},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
],
}
]
firstIndex = 0, secondIndex = 1
const result = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
{id: 23, value: c},
],
}
]
const result = array.map((el, i) => (i === firstIndex) && el.rows.map(elm, (elm, index) => (index === secondIndex ) && elm.splice(index, 1)
))
Active menu item NOT based on URL but based on a variable
I want to have a Menu with active items on my website. It should be added a class to activate the item. Since the project has cryptic URLs, URL-based solutions are not possible. The text of the respective menu item is shown in the respective page title.
My idea was to compare the pagetitle id="navtopheader"
with the text in the menu item. If it is equal, add the menuactive
class to the respective menu item.
My HTML looks basically like this:
<div id="navtopheader" class="navtopheader">menu item 1</div>
...
<div class="nav_ebene_2">
<p>menu item 1</p>
</div>
<div class="nav_ebene_2">
<p>menu item 2</p>
</div>
...
I can do it actually in an inefficient way:
var headertext = document.getElementById("navtopheader").innerText
var menutext0 = document.getElementsByClassName("nav_ebene_2")[0].innerText
var navlist = document.getElementsByClassName("nav_ebene_2");
if (headertext == menutext0) {
navlist[0].classList.add("activemenu");
}
var menuitem1 = document.getElementsByClassName("nav_ebene_2")[1].innerText
if (headertext == menuitem1) {
navlist[1].classList.add("activemenu");
}
...
But since the number of menu items varies across the website, i would get an error message if i include too much/too few menu items.
Is there an appropriate solution? I tried the whole day but didn’t solve the problem. Thank you!
get value in input field from virtual keyboard in react
I am working on a countdown watch which have a virtual numpad (given in code as button) and three input (hour,minute and second). now i want that whenever i click input box and type in virtual numpad ,it print the value in that box only.
- there i used three ref to getElement of input and change set their value but dont know how to set for specific box
const inputOne = useRef(null);
const inputTwo = useRef(null);
const inputThree = useRef(null);
const changeValue = (val) => {
inputOne.current.value = setTime({hour: updatedHour + val, minute: updatedMinute, second: updatedSecond});
inputTwo.current.value = setTime({hour: updatedHour, minute: updatedMinute + val, second: updatedSecond});
inputThree.current.value = setTime({hour: updatedHour, minute: updatedMinute, second: updatedSecond + val});
}
const changeTime = (e) => {
setTime({ ...time, [e.target.name]: e.target.value });
};
- this is input fields i use , updatedHour,updatedMinute and updatedSecond is part of setTime state.
<input ref={props.inputOne} onChange={props.changeTime} name="hour" placeholder="Hour" value={props.updatedHour} />
<input ref={props.inputTwo} onChange={props.changeTime} name="minute" placeholder="Minute" value={props.updatedMinute} />
<input ref={props.inputThree} onChange={props.changeTime} name="second" placeholder="Second" value={props.updatedSecond} />
- this is buttons which create virtual keyboard
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('1')}>1</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('2')}>2</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('3')}>3</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('4')}>4</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('5')}>5</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('6')}>6</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('7')}>7</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('8')}>8</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('9')}>9</button>
<button className="grid-item" tpye='button' >Prev</button>
<button className="grid-item" tpye='button' onClick={()=> props.changeValue('0')}>0</button>
<button className="grid-item" tpye='button' >Next</button>
Highlight an individual character of text block containing links and heading on mouse hover
I am trying to achieve that when hover over a character, the character should change its color. It should work on individual character , links, heading etc.
My following code gives me result that i want but it removes the links and headings.
JS Fiddle: http://jsfiddle.net/bvpodc6z/1/
HTML CODE
<div class="words">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
<a href="#link">LINK</a>
<h1>
Heading
</h1>
Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
</div>
JS Code
$cont = $('.words');
parts = $.map($cont.text().split(''), function(v){
return $('<span />', {text:v});
});
$cont.empty().append(parts);
CSS Code
.words span:hover{color:#F00}
How to read an array inside another array in an ” Json object” -> Jade/PUG.js
I’m trying to “create” a template using “Json” in Pug, but there is a point where I need to put much Information. But the problem for me becomes where I need to read an element deeply inside.
-
var SuperSlidersInfo = {
'numero': '4',
'sectionName': 'Dignidad',
'video': true,
'youtube': [
'idVideo',
'idVideo2',
],
'notes':[
['prueba1', 'prueba2'],
['segundo1', 'segundo2', 'segundo3'],
],
'img': [
'NombreImagen',
'NombreImagen2',
],
'extension': 'jpg',
'titulo': [
'Titulo',
],
'parrafo': [
'Texto',
]}
+SuperSlidersPug(SuperSlidersInfo)
mixin SuperSlidersPug(SuperSlidersInfo)
.container-pc
.container-sliderAutomatico.no-phone
div(id=`sliderAutomatico${SuperSlidersInfo.numero}` class= SuperSlidersInfo.video ? "dosVideos-container" : "otraCosa").sliderAutomatico
each imgName, index in SuperSlidersInfo.img
//- div(class= SuperSlidersInfo.video ? "dosVideos").sliderAutomatico__section
div(class= SuperSlidersInfo.video ? "dosVideos" : "otraCosa").sliderAutomatico__section
.swiper-content
if SuperSlidersInfo.video
.section_videoContainer
a(href=`#video${SuperSlidersInfo.sectionName}${index}`).section_videoThumbnail--Container
img(src=`${imgURL}${SuperSlidersInfo.sectionName}${index + 1}.${SuperSlidersInfo.extension}`, alt="")
h3.swiper-content_titulo= `${SuperSlidersInfo.titulo[index]}`
.section_video--notes
//- -----------------
//- Problem
//- -----------------
//- the "a" below works, but I need to "create" and each, or for, or any loop for to put all the elements in that especific array.
//- a(href=`${SuperSlidersInfo.notes[index]}`).section_video--note
//- The "each" below it suppose to works. But when I put the "[index]" it brokes..
each note, noteIndex in SuperSlidersInfo.notes[index]
a(href=`${note}`).section_video--note
For general elements it works well. But when I need to read the “notes”. It’s impossible por me.
But when I put each note, noteIndex in SuperSlidersInfo.notes[index]
everything is broken…
So I need to read the “elements” that “note” has in its array…
//- Works well
each note, noteIndex in SuperSlidersInfo.notes
//- It's Broke
each note, noteIndex in SuperSlidersInfo.notes[index]
the index
is from the each
that exist almost at top of the code
For loops and if statements
I have a character on screen that I’m trying to make it collect collectable items, however, with the if
statement in the for
loop present, it makes all the collectables disappear from screen; and without it, the collectables are drawn, but I’m only able to collect 1 and the other 2 disappear. The objective is the get the array to loop over and draw the collectables and have the collectables disappear as the game character walks over them.
var collectable
function setup(){
collectable = false
collectable = [
{ collectable_x_pos: 1220, collectable_y_pos: 100, isFound: false },
{ collectable_x_pos: 220, collectable_y_pos: 100, isFound: false },
{ collectable_x_pos: 1820, collectable_y_pos: 100, isFound: false },
];
}
function draw(){
if (collectable.isFound == false) {
for (var i = 0; i < collectable.length; i++) {
drawCollectable(collectable[i]);
checkCollectable(collectable[i]);
}
}
function drawCollectable(t_collectable) {
fill(0, 255, 255);
quad(
t_collectable.collectable_x_pos - 70,
t_collectable.collectable_y_pos + 277,
t_collectable.collectable_x_pos - 54,
t_collectable.collectable_y_pos + 331,
t_collectable.collectable_x_pos - 36,
t_collectable.collectable_y_pos + 277,
t_collectable.collectable_x_pos - 54,
t_collectable.collectable_y_pos + 222
);
}
function checkCollectable(t_collectable) {
if (
dist(gameChar_x, gameChar_y, t_collectable.x_pos, t_collectable.y_pos) < 20
) {
console.log("Collected");
collectable.isFound = true;
}
}
JavaScript conditional font color change of part of text
I tried to change the font color of my String in my vue application based on a condition. However, the solutions I found so far changed the color for the whole text. I only want specific parts to be changed. For example:
const exampleString= 'Yesterday I was ACTIVITY with FRIEND who I first met in PLACE'
The words in capital letters should be in color red but the rest in black. So a condition like “if three subsequent chars are capital letters than color red until empty space”. Is there a way to implement this ?
Submitting form with js while ? is missing in the return result
I write a form submit thread with the attr method:
var href = a.attr('href');
if(href =='') return;
if(href.startsWith('http') || href.startsWith('//:')){
a.attr('href',href.trim());
if(href.indexOf(location.hostname) > -1){
return;
}
if(href.indexOf('<?php echo $_SERVER['SERVER_NAME']; ?>') > -1){
return;
}
a.attr('href','go.htm?uri='+href);
a.attr('rel','nofollow');
}
However, it returns the URL without ?, for example, I want to return https://example.abc.com/?ref=abc, the return result will be https://example.abc.com/ref=abc without “?” the question mark.
I’m struggling with solving this and I appreciate any helpful tips.