I have embedded a chat window to my website with iframe that consists of a chat icon and on click of that, the chat window gets opened. I want that the iframe would always take minimal width and height to show the chat icon and chat window respectively.
Category: javascript
Category Added in a WPeMatico Campaign
onClick in React changes all of the classes states in react
I have creates a aside in react and I want to change their state to active when clicked on each of them, but when I click on any item all
of them suddenly get activated. how to fix this?
import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";
// * api
import { getCoin } from "../services/api";
// *spinner
import Loader from "./Loader";
const Company = () => {
const [changeClass, setChangeClass] = useState(false);
const [coins, setCoins] = useState([]);
useEffect(() => {
const fetchAPI = async () => {
const data = await getCoin();
setCoins(data);
};
fetchAPI();
}, []);
const myHandler = () => {
setChangeClass(true);
console.log("trued");
};
const myHandler2 = () => {
console.log();
};
return (
<>
{coins.length ? (
coins.map((coin) => (
<Row
className={
changeClass
? "p-2 border-top d-flex align-items-center company-list-single-active"
: "p-2 border-top d-flex align-items-center company-list-single"
}
onClick={() => {
myHandler();
myHandler2();
}}
key={coin.id}
>
<Col xxl="2" xl="2" lg="2" md="2" sm="2" xs="2">
<Image
src={coin.image}
alt={coin.name}
className="coin-image mx-2"
fluid
/>
</Col>
<Col>
<span>{coin.name}</span>
</Col>
</Row>
))
) : (
<Loader />
)}
</>
);
};
export default Company;
plese help me for fixed bug
thanks
plese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanksplese help me for fixed bug
thanks
Close button doesn’t work on many Android devices (jQuery UI Draggable Function)
This is my code:
function setToTop(t) {
var n = 0;
$(".box").each(function(t, o) {
var e = Number.parseInt($(o).css("z-index"));
e = Number.isNaN(e) ? 0 : e, n = Math.max(n, e)
}), t.css({
zIndex: n + 1
})
}
$(function() {
$(document).mouseleave(function() {
$(document).trigger("mouseup")
}), $(".box").draggable({
helper: "original",
containment: "body",
drag: function(t, n) {
n.offset.left < 0 && (n.position.left = n.position.left - n.offset.left)
},
stop: function(t, n) {},
start: function(t, n) {
setToTop(n.helper)
}
})
}), $(".box span").click(function() {
$(this).parents(".box").css("display", "none")
});
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
font-size: 50px;
font-family: Arial;
background-color: rgb(220, 220, 220);
}
.box {
background-color: yellow;
color: black;
padding: 20px;
display: block;
position: absolute;
border: 2px black;
cursor: all-scroll;
border: 1px solid black;
}
.box:nth-child(1) {
left: 20%;
top: 10%;
}
.box:nth-child(2) {
left: 10%;
top: 15%;
}
.box:nth-child(3) {
left: 25%;
top: 30%;
}
.box:nth-child(4) {
left: 30%;
top: 20%;
}
.box span {
background-color: red;
color: white;
position: absolute;
top: -40px;
right: -40px;
padding: 10px;
cursor: pointer;
border: 1px solid black;
}
<div class="box">Hello <span>✕</span></div>
<div class="box">Love <span>✕</span></div>
<div class="box">Freedom <span>✕</span></div>
<div class="box">Peace <span>✕</span></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js" integrity="sha256-hlKLmzaRlE8SCJC1Kw8zoUbU8BxA+8kR3gseuKfMjxA=" crossorigin="anonymous"></script>
<script src="https://raw.githubusercontent.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.min.js"></script>
The function is:
- to have draggable boxes
- the currently dragged box gets set on top
- closing a box is possible with the
✕
button
Unfortunately, the ✕
button doesn’t work on many touch devices. My research has shown that it works well on Apple devices, but pretty bad on many Android devices.
Has anyone an idea to fix that? Also, does anyone have an idea to optimize the code?
Would be very thankful for help! <3
Hide edge labels in vis.js-network
I would like to simply show/hide the labels of the edges of my vis.js-network – is this possible?
I have tried to update the edges in the vis.js-data structure:
- Delete the
label
property – doesn’t work - Set the
label
toundefined
– doesn’t work - Set the
label
to''
– doesn’t work - Set the
label
to' '
– works
I would prefer a network-wise toggle of some kind, but I haven’t found one.
Is there a better way of doing this?
How to achieve multi-line output with formatting in JavaScript
I am experimenting with the following codepen.io trinket and trying to achieve multiline output with formatting for the JavaScript text that is returned in response to user-input.
For instance, if the user types “/engage” the following text is returned:
“Follow the white rabbit. I want this to be the second line”
The code is below. I would like the above text to:
a) be output on two separate lines with my being able to control the breaks between lines (like br in HTML)
b) allow some basic formatting – specifically to add bold formatting to the word “rabbit”.
c) allow for changing the font size of “follow” to a larger font/or different style etc.
I have tried various things but they all come up with errors.
RELEVANT CODE
submitForm.addEventListener("submit", function(e) {
e.preventDefault();
if (input.value === "/clear") {
clearCommand();
} else if (input.value === "/list" || input.value === "help") {
listAllCommands();
} else if (input.value === "/connect") {
goProgress();
} else if (input.value === "/engage") {
matrixEffect();
clearCommand();
textArea.value = "Follow the white rabbit. I want this to be the second line"
} else {
textArea.value +=
"nERROR: Unknown command! Type 'help' for list of commands.";
input.value = "";
}
textArea.scrollTop = textArea.scrollHeight;
});
CODEPEN ENTIRE SNIPPET
Can not populate nested array in mongoose
I try to populate products data in order. I use mongoose with nestjs and graphql. The problem is that I don’t want to create new collection. So all I want to do is to create an order which has attribute orderedProductArray
. This consists of product
and amount
. Product has a reference to Product
object.
Schemas
@Schema()
export class OrderedProduct {
@Prop(() => ID)
_id: string
@Prop(() => Int)
amount: string
@Prop({ type: Types.ObjectId, ref: Cloth.name })
product: Cloth
}
export const OrderedProductSchema = SchemaFactory.createForClass(OrderedProduct)
@Schema()
export class Order {
@Prop()
_id: string
@Prop({ type: Date, default: Date.now })
confirmedDate: Date
@Prop({ type: Types.ObjectId, ref: OrderStatus.name })
orderStatus: OrderStatus
@Prop()
userName: string
@Prop()
email: string
@Prop()
phoneNumber: string
@Prop({ type: [OrderedProductSchema] })
orderedProductArray: [OrderedProduct]
}
export const OrderSchema = SchemaFactory.createForClass(Order)
And the service:
async getOrderById(getByIdArgs: GetOrderByIdArgs): Promise<Order> {
try {
const searchedOrderId = await this.orderModel
.findById(getByIdArgs)
.populate({
path: 'orderedProductArray',
populate: {
path: 'product._id',
model: 'Cloth'
}
})
.exec()
if (searchedOrderId) {
return searchedOrderId
}
throw new NotFoundException('The given id does not exist')
} catch (error) {
throw new NotFoundException(error)
}
I will be appreciated for your help. I tried almost everything that I’ve found in StackOverflow. Thanks in advance!!!
Why does only the first filter for “show more” work?
On the webshop for my internship I’m trying to resolve a filter problem.
On each page, only the first filter works when you press “show more”. On all other filters nothing happens once you press “show more”.
This is the code responsible:
function _toConsumableArray(e) {
if (Array.isArray(e)) {
for (var o = 0, s = Array(e.length); o < e.length; o++) s[o] = e[o];
return s;
}
return Array.from(e);
}
function showLessMore(e) {
var o = e.target;
if (qty.hasClass("js-hook__amshopby-more")) {
e.preventDefault();
var s = o.parentNode.parentNode,
a = s.querySelectorAll(".js-hook__amshopby-item");
if (a.length) {
for (var r = [].concat(_toConsumableArray(a)), t = 0; t < r.length; t++) {
var l = r[t];
"none" == l.style.display && (l.classList.add("filter--visible"), (l.style.display = "block"));
}
(o.style.display = "none !important"), (s.querySelector(".js-hook__amshopby-less").style.display = "block !important");
}
}
if (qty.hasClass(o, "js-hook__amshopby-less")) {
e.preventDefault();
var n = o.parentNode.parentNode,
y = n.parentNode.parentNode.querySelectorAll(".js-hook__amshopby-item.filter--visible");
if (y.length) {
for (var i = [].concat(_toConsumableArray(y)), p = 0; p < i.length; p++) {
var c = i[p];
c.classList.remove("filter--visible"), (c.style.display = "none");
}
(o.style.display = "none !important"), (n.querySelector(".js-hook__amshopby-more").style.display = "block !important");
}
}
}
Any help would be greatly appreciated!
Registering pre keys with server in signal protocol
I was recently going through documentation of signal protocol. https://github.com/signalapp/libsignal-protocol-javascript. In the documentation after they generate the pre key bundles and other things they say “// Register preKeys and signedPreKey with the server”. But there is no mention of how to do that. Apart from this can anyone please help me with how to know a users recipient id to decrypt his message. Also are the keys permanent or they disappear on closure of browser.
How to change bar width of a specific series while in different axis target – Angular google charts
I am developing a layered column chart using ComboChart on Angular google charts. Although I’ve separated two series of bar charts in two different axis, being able to find a bar in front of the other, like needed, I can’t change the width of one of the series only. I want a result like the amCharts Layered Column Chart:
Right now, the chart looks like:
Current chart – Angular google charts
Also, if there is a way to share the same y axis while keeping one bar in front of the other, instead of staking then, it would be great.
The code I’ve been using for options of the angular google chart:
this.options =
{
colors: ['#1E90FF', '#f39800'],
hAxis: {
title: 'haxisTitle',
type: 'category'
},
vAxis:{
title: 'Value',
minValue: 0,
format: this.numberFormat
},
seriesType: 'bars',
bar: {1: {groupWidth: "30"}},
series:
{
0: {
targetAxisIndex: 0
},
1: {
targetAxisIndex: 1,
}
},
vAxes: {
0: {
title: 'Altered Value',
label:'Altered Value',
viewWindow: { // <-- set view window
min: 0,
max: this.maxValue + 0.1*this.maxValue, // Sets the maximun value of altered or real value to the window size (both axis)
},
format: this.numberFormat,
type: 'bars'
},
1: {
title: 'Real Value',
label:'Real Value',
viewWindow: { // <-- set view window
min: 0,
max: this.maxValue + 0.1*this.maxValue,
},
format: this.numberFormat,
type: 'bars'
}
},
aggregationTarget: 'auto',
stackSeries: true,
isStacked : true,
explorer: {
actions: ['dragToZoom', 'rightClickToReset'],
keepInBounds: true,
maxZoomIn: 4.0
}
};
}
The chart shows the data correctly, the only problem is the layout.
Some reference that might help:
Google Developers – Visualization: Combo Chart
amCharts Layered Column chart
Overlapped bars – Stack overflow quote – Here the result was a stacked bar chart (something I don’t want)
Stop clock when page is not on screen [duplicate]
in the title I used a clock as an example but my question is for all functions.
How do I stop some function when it is not on-screen. For the clock I used the useEffect
Hook with setInterval()
, since I am using ReactJs. So how do I stop the interval when the page is not visible on the screen so it does not slow down the users computer. I read that it is not possible to stop setInterval so I know that I need to clearInterval
and and setInterval
again.
Java script XMLHttpRequest
My code is not working when I uploaded it to the hosting site but it is 100% working in localhost. What’s wrong with my code?
var questionno="1";
load_questions(questionno);
function load_questions(questionno)
{
document.getElementById("current_que").innerHTML=questionno;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText=="over")
{
window.location="result.php";
}
else
{
document.getElementById("load_questions").innerHTML=xmlhttp.responseText;
load_total_que();
}
}
};
xmlhttp.open("GET","load_questions.php?questionno="+ questionno,true);
xmlhttp.send(null);
}
Why is my setter function provided by the context api not working in the handle function
I have this implementation for a search filter using tags.
https://codesandbox.io/s/search-filter-tags-zgfcs?file=/src/Tags.tsx:622-626
I for the life of me cannot figure out why my setTags() method is not working in the handleChange function, but is working fine in the handleAllChange function.
Tags.tsx
import * as React from "react";
import { TagContext } from "./TagContext";
let AllTags = [
"Html",
"CSS",
"JavaScript",
"ReactJS",
"GitHub",
"TypeScript",
"Celebal"
];
const Tags = () => {
const { tags, setTags } = React.useContext(TagContext);
const [allChecked, setAllChecked] = React.useState(false);
// const [tags, setTags] = React.useState([] as string[]);
const handleAllChange = () => {
if (!allChecked) {
setTags(AllTags);
} else {
setTags([]);
}
setAllChecked(!allChecked);
};
const handleChange = (name: string) => {
let temp = tags;
if (temp.includes(name)) {
temp.splice(temp.indexOf(name), 1);
} else {
temp.push(name);
}
console.log("temp - ", temp);
setTags(temp);
};
React.useEffect(() => {
console.log("Tags - ", tags);
}, [tags]);
return (
<>
<h1>Filter Tags</h1>
<div className="tags-container">
<div className="w-fit p-2 m-2">
<button
className="p-1 border-2 border-black rounded font-semibold"
onClick={handleAllChange}
>
Apply All
</button>
</div>
{AllTags.map((tag, i) => {
return (
<div className="w-fit p-2 m-2" key={i}>
<input
className="mt-2"
type="checkbox"
value={tag}
name={tag}
onChange={(e) => handleChange(tag)}
checked={tags.includes(tag)}
/>
<label htmlFor={tag}>#{tag}</label>
</div>
);
})}
</div>
</>
);
};
export default Tags;
The tags, and setTags are coming from context API.
TagContext.tsx
import * as React from "react";
interface ITagContext {
tags: any;
setTags: any;
handleChange: (name: string) => void;
}
export const TagContext = React.createContext({} as ITagContext);
interface ITagProvider {
children: React.ReactNode;
}
export const TagProvider = ({ children }: ITagProvider) => {
const [tags, setTags] = React.useState([] as string[]);
const handleChange = (name: string) => {
debugger;
let tag = name;
let temp = tags;
if (temp.includes(tag)) {
temp.splice(temp.indexOf(tag), 1);
} else {
temp.push(tag.toString());
}
setTags(temp);
};
React.useEffect(() => {
debugger;
console.log("Tags in Context - ", tags);
}, [tags]);
return (
<TagContext.Provider value={{ tags, setTags, handleChange }}>
{children}
</TagContext.Provider>
);
};
combine new line json into one array
I have a JSON from web server that looks like this:
{"timestamp":1642069251.6908009,"station_id":"ORBB","channel":5,"freq":131.725,"level":-28.1,"error":0,"mode":"2","label":"Q0","block_id":"8","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S10A"}
{"timestamp":1642069257.00876,"station_id":"ORBB","channel":5,"freq":131.725,"level":-41.3,"error":0,"mode":"2","label":"Q0","block_id":"7","ack":false,"tail":"PH-HXO","flight":"HV6905","msgno":"S28A"}
{"timestamp":1642069259.057013,"station_id":"ORBB","channel":5,"freq":131.725,"level":-24.9,"error":0,"mode":"D","label":"Q0","block_id":"9","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S11A"}
l have followed this answer but l have nothing to show in console.
l cant edit the data JSON above to deliver a valid JSON because it’s coming from a data server using ajax .
$.ajax('acarsdec.json', {
type: 'GET',
dataType: "json",
timeout: 10000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
console.log(data)
var lines = data.split(/n/);
var wrapped = "[" + lines.join(",") + "]";
var obj = JSON.parse(wrapped);
console.log(obj)
})
Firebase onSnapshot listener: How to handle if doc does not exist yet?
I am building an app where users can tag subjects they are interested in.
I am looking for best practices on how to handle the following issue:
I have a page that mounts an onSnapshot listener during page creation (example page path: site.com/tags/apple
). This page allows the user to actually add the tag to their feed. First, I need to “watch” whether they add the tag to their feed or check to see if it already exists so that way I can toggle the state of a button icon to let them know that they already have added this tag to their feed.
I thought I’d use the onSnapshot
listener to handle this logic like so (simplified for this question):
mounted() {
loadwatchedTag() {
const docRef = doc(db, `users/${this.userProfile.uid}/tags`, 'apple') //<-- example tag
this.unsubscribe = onSnapshot(docRef, {
next: (doc) => console.log('tag', doc.data()),
error: (error) =>
console.log('watchedTag listener error', error)
})
}
}
The problem is that on page load, I get the following error in console (because the tag does not yet exist):
tag, undefined
So, how to handle this issue on page load if the tag does not yet exist? Should I be doing something like this within the onSnapshot code?
if (docSnap.exists()) {
console.log("tag exists!", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("tag does not exist");
}
How to use setInterval with react useEffect hook correctly?
I tried to create a simple timer app with ReactJS and found the below code on the internet.
Does the function that we passed to the useEffect
will execute with the dependency change or does it recreates with every dependency change and then execute?
Also I console log the return function of the useEffect
and it runs with every render. Does it run only when the component unmount? or with every render?
import { useEffect, useState } from "react";
const App = () => {
const [isActive, setIsActive] = React.useState(false);
const [isPaused, setIsPaused] = React.useState(true);
const [time, setTime] = React.useState(0);
React.useEffect(() => {
let interval = null;
if (isActive && isPaused === false) {
interval = setInterval(() => {
setTime((time) => time + 10);
}, 10);
} else {
clearInterval(interval);
}
return () => {
console.log("cleanup");
clearInterval(interval);
};
}, [isActive, isPaused]);
const handleStart = () => {
setIsActive(true);
setIsPaused(false);
};
const handlePauseResume = () => {
setIsPaused(!isPaused);
};
const handleReset = () => {
setIsActive(false);
setTime(0);
};
return (
<div className="stop-watch">
{time}
<button onClick={handleStart}>start</button>
<button onClick={handlePauseResume}>pause</button>
<button onClick={handleReset}>clear</button>
</div>
);
};
export default App;