Can we use useState() at multiple time or is there any limit to use it in single component in React Js.
Category: javascript
Category Added in a WPeMatico Campaign
Physics of Messenger Chatheads
I’ve searched long and hard about the physics and programming of messenger chathead/chatbubble but I couldn’t find any resource that could show how the “physics” of the chathead works. I am talking about the way they compute the bouncyness of the chathead and computing the trajectory of the bubble, also the velocity according to the speed of the flick of the finger. I am going to risk it and post this question here in SO. Can anyone help me figure out the physics and programming behind it? has anybody tried hacking the source code of the mobile app of messenger to figure this one out?
Is there an idiomatic way to prevent recursive function calls in JavaScript?
Say I have some complicated function that, through subsequent nested function calls, can potentially call itself, is there an accepted method to prevent this recursive call in the case where it is undesirable?
e.g.:
function h()
{
if(someOtherState)
f(); // uh-oh
}
function g()
{
if(someState)
h();
}
function f()
{
g();
}
To save values changes from JSON
I’m using a webapp, for each event I’d like to save to other sheet the changes minute by minute.
What is the correct approach to start from?
I get the data from my webapp.
const getJson = () => {
const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Live");
let options = {
method: "GET"
,headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}
,muteHttpExceptions: true
};
let url = "webappurl";
try {
let response = UrlFetchApp.fetch(url, options);
if(response){
let data = JSON.parse(response.getContentText()).result;
const headers = Object.keys(data.reduce((o,e) => (Object.keys(e).forEach((k) => (o[k] = true)),o), []));
const toSheet = [headers,...data.map((o) => headers.map((k) => o[k] || null))];
ss.getRange("A1:AA").clearContent();
if (toSheet.length > 0) {ss.getRange(1,1,toSheet.length,toSheet[0].length).setValues(toSheet)}
} else {getJson()}} catch (e){};
}
I share the sheet for you as editors
https://docs.google.com/spreadsheets/d/1Nq6liBgKwL1PbTFrEzclAn_umpq10uW28uPR_NnCbgA
Any opinion is appreciated
How can I disable/enable time and date
How can I disable/enable time and date, for example 07/07/2022 12:00PM is off but on 08/07/2022?
I want disable time by date
but I can not why?
Below is an example which enables/disables the button according to the specified enableTime and disableTime(I’m disabling/enabling BtnExit)
this my script function
$(document).ready(function() {
if (localStorage.getItem("itmEmployee") == "12:00PM")
$("#employed_v0").prop("checked", true);
else
$("#employed_v1").prop("checked", true);
if (localStorage.getItem("itmEmployee") == "12:00PM")
$('#datetimepicker').datetimepicker({
format: 'DD/MM/YYYY'
});
if (localStorage.getItem("itmEmployee") == "12:00PM")
$("#12").prop("disabled", false);
else
$("#12").prop("disabled", true);
$("#12").val(localStorage.getItem("itmTest"));
$("[name=employed]").on("change", function() {
localStorage.setItem("itmEmployee", $(this).val());
if ($(this).val() == "12:00PM")
$("#12").prop("disabled", false);
else
$("#12").prop("disabled", true);
});
$("#12").on("change", function() {
localStorage.setItem("itmTest", $(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Date<span>*</span></label>
<input id="datepicker" name="r_date" type="date" required> here we will close it using checkbox
<input type="checkbox" name="employed" id="employed_v1" value="12:00PMM" /> 12:00 PM disable
<input type="checkbox" name="employed" id="employed_v0" value="12:00PM" /> 12:00 PM enable
<select id="all">
<option>Select</option>
<option id="12">12:00 PM</option>
</select>
</div>
Webpack 5 build disables all onclicks
I am making a small React app with minimal React modules using Webpack 5 as the bundler. I am having an issue with my build files.
If the build files are not deferred in the index.html, everything is working fine. AKA my development files are fine. After running the build, all my events (onClick, onMouseOver, etc.) no longer work.
I have a warning saying that the build size is too large but it doesnt explain the events that are no longer functioning.
One of them is:
<div className='connectDiv'>
<button className='btnConnect'
onMouseOver={() => btnText('mouseOver')}
onMouseOut={() => btnText('mouseOut')}
onClick={() => aircallAPIping()}
style={btnStyle}>
{buttonText}
</button>
</div>
With the function being:
function btnText(action) {
if(buttonText === 'Connected' && action === 'mouseOver') {
setText('Disconnect');
setStyle({backgroundColor:'orange',color:'white'});
};
if(buttonText === 'Disconnect' && action === 'mouseOut') {
setText('Connected');
setStyle({backgroundColor:'green',color:'white'});
};
if(buttonText === 'Not Connected' && action == 'mouseOver') {
setText('Connect');
setStyle({backgroundColor:'orange',color:'white'});
};
if(buttonText === 'Connect' && action == 'mouseOut') {
setText('Not Connected');
setStyle({backgroundColor:'white',color:'#74787d'});
};
};
I have a App.js AND a main.js file in the src folder. Does that collide with each other?
My webpack configuration is:
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
entry: [ "@babel/polyfill", path.resolve(__dirname, './src/main.js')],
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
},
},
],
},
{
test: /.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /.html$/,
exclude: [/node_modules/, require.resolve('./public/index.html')],
use: [
{
loader: "html-loader",
options: {
name: '[name].[ext]'
},
}
]
}
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, './public'),
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
static: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html"
})
]
};
Does anyone have/had the same issue? And what can be done about it?
Thanks a lot.
Check condition for imbricated property in object [duplicate]
I want to use the following condition
if (this.solvedConflictsDetails[this.instance.instanceId][this.model.name][this.entity.entityId].solved)
The problem is that if one of the above doesn’t exist in the object it will say cannot read undefined
How would you check a condition like this?
Using Mixitup with multiple custom styled select dropdowns
I’m using MixitUp with the multifilter extension to filter some of the room types in a site I’m developing. The CMS is WordPress so the general integration is easy and was working until introducing custom styled select dropdowns.
I’ve found a jQuery script that generates custom styled select dropdown lists – this leads me to my issue of having mixitup do it’s thing when selecting an option from any of the dropdowns, as the jQuery replicates a div based version of the select menu it no longer works. Even when I try and console.log something I’m not getting anything through.
This is the template part to generate the is as follows:
<section class="relative bg-white-th lg:pb-16 pb-12">
<div class="container lg:mb-24 xl:px-0 lg:px-4 px-8">
<form action="" class="flex flex-row flex-wrap items-center">
<div class="lg:w-1/3 w-1/2 lg:pr-4 pr-1 lg:mb-0 mb-8">
<label for="people" class="uppercase lg:mb-4 opacity-40 lg:text-base text-sm">Book with us</label>
<select name="people" id="No. of People" class="search-select custom-select" data-filter-group data-logic="and">
<option value="">No. of People</option>
<option value=".people-2">Up 1 People</option>
<option value=".people-2">Up 2 People</option>
<option value=".people-4">Up 3 People</option>
<option value=".people-4">Up 4 People</option>
</select>
</div>
<div class="lg:w-1/3 w-1/2 lg:pr-2 pr-1 lg:mb-0 mb-8">
<label for="price" class="uppercase lg:mb-4 opacity-40 lg:text-base text-sm">Price</label>
<select name="price" id="Per Night" class="search-select custom-select" data-filter-group data-logic="and">
<option value="">Per Night</option>
<option value=".price-130">£130+ Per Night</option>
<option value=".price-140">£140+ Per Night</option>
<option value=".price-160">£160+ Per Night</option>
<option value=".price-180">£180+ Per Night</option>
</select>
</div>
<div class="lg:w-1/3 w-1/2 lg:pl-2 pl-1 lg:mb-0 mb-8">
<label for="features" class="uppercase lg:mb-4 opacity-40 lg:text-base text-sm">Features</label>
<select name="features" id="Features" class="search-select custom-select" data-filter-group data-logic="and">
<option value="">Features</option>
<option value=".disabled">Disabled Access</option>
<option value=".dog-friendly">Dog Friendly</option>
<option value=".ground-floor">Ground Floor</option>
<option value=".interlink-door">Interlink Door</option>
</select>
</div>
</form>
</div>
<div class="container lg:px-0 px-8" id="filter-container">
<?php
while(have_rows('rooms')) : the_row();
$post_object = get_sub_field('room');
$post = $post_object;
setup_postdata( $post );
$sleeps = get_field('sleeps');
$from = get_field('from');
$pets = get_field('pets');
$description = get_field('description');
$booking_link = get_field('booking_link');
$location = get_field('location');
?>
<div class="relative w-full lg:mb-16 mb-12 flex lg:flex-row flex-col mix price-<?php echo $from ?> people-<?php echo $sleeps ?>
<?php while(have_rows('features_list')) : the_row();
$features = get_sub_field('feature');
$mod_name = strtolower(str_replace(' ', '-', $features));
;?> <?php echo $mod_name ?><?php endwhile;?>">
<div class="lg:w-1/2 w-full relative search-image">
<img src="<?php the_post_thumbnail_url(); ?>" alt="Thumbnail Image" class="absolute object-cover w-full h-full">
</div>
<div class="lg:w-1/2 w-full relative lg:p-8">
<div class="w-full flex flex-row items-center justify-between mb-8">
<h4 class="text-3xl mb-2"><?php the_title(); ?></h4>
<svg class="accomo-fav" id="<?php the_ID(); ?>" width="22" height="21" viewBox="0 0 22 21" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.5 1C13.76 1 12.09 1.81 11 3.09C9.91 1.81 8.24 1 6.5 1C3.42 1 1 3.42 1 6.5C1 10.28 4.4 13.36 9.55 18.04L11 19.35L12.45 18.03C17.6 13.36 21 10.28 21 6.5C21 3.42 18.58 1 15.5 1Z" stroke="black" stroke-width="2" stroke-linejoin="round"/>
<path d="M15.5 1C13.76 1 12.09 1.81 11 3.09C9.91 1.81 8.24 1 6.5 1C3.42 1 1 3.42 1 6.5C1 10.28 4.4 13.36 9.55 18.04L11 19.35L12.45 18.03C17.6 13.36 21 10.28 21 6.5C21 3.42 18.58 1 15.5 1Z" stroke="black" stroke-width="2" stroke-linejoin="round"/>
</svg>
</div>
<p class="uppercase text-orange-th lg:mb-8"><?php echo $location ?></p>
<p class="mb-2"><strong>Sleeps:</strong> Up to <?php echo $sleeps ?></p>
<p class="mb-2"><strong>From:</strong> £<?php echo $from ?> per night</p>
<p class="mb-8"><strong>Features:</strong>
<?php
$i = 0;
$count = count(get_sub_field('features_list'));
while(have_rows('features_list')) : the_row();
$i++;
$feature = get_sub_field('feature');
?>
<span><?php echo $feature ?>,</span>
<?php
endwhile;
?>
</p>
<p class="mb-8"><?php echo $description ?></p>
<div class="w-full flex lg:flex-row flex-col">
<a href="<?php the_permalink(); ?>" class="btn-primary-transparent lg:w-auto w-full lg:mr-4 mr-0 lg:mb-0 mb-3">View Rooms</a>
<a href="hidden for privacy" target="_blank" class="btn-primary-transparent lg:w-auto w-full">Book Now</a>
</div>
</div>
</div>
<?php
wp_reset_postdata();
endwhile;
?>
</div>
</section>
This is the script for the MixitUp – it’s located on the template part itself:
<script>
$(function(){
var containerEl = document.querySelector('#filter-container');
var mixer = mixitup(containerEl, {
controls: {
toggleLogic: 'and'
},
multifilter: {
enable: true
}
});
$('.custom-option').on('click', function() {
var filterString = $('.selection').data('value')
// var filterString = $(this).data('value') have also tried this as well to no avail
console.log(filterString)
mixer.filter(filterString);
});
});
</script>
And this is the script that generates the custom select dropdowns:
$(".custom-select").each(function() {
var classes = $(this).attr("class"),
id = $(this).attr("id"),
name = $(this).attr("name");
var template = '<div class="' + classes + '">';
template += '<span class="custom-select-trigger">' + $(this).attr('id') + '</span>';
template += '<div class="custom-options">';
$(this).find("option").each(function() {
template += '<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>';
});
template += '</div></div>';
$(this).wrap('<div class="custom-select-wrapper"></div>');
$(this).hide();
$(this).after(template);
});
$(".custom-option:first-of-type").hover(function() {
$(this).parents(".custom-options").addClass("option-hover");
}, function() {
$(this).parents(".custom-options").removeClass("option-hover");
});
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
$(".custom-option").on("click", function() {
$(this).parents(".custom-select-wrapper").find("select").val($(this).data("value"));
$(this).parents(".custom-options").find(".custom-option").removeClass("selection");
$(this).addClass("selection");
$(this).parents(".custom-select").removeClass("opened");
$(this).parents(".custom-select").find(".custom-select-trigger").text($(this).text());
});
So currently when a .custom-option class is clicked on, nothing seems to happen, I’ve tried creating a single function to handle just logging a string message on click and it just seems to do nothing, once I can somehow pass this value across then I should be find to create the same mixer string that I used before to make the MixitUp section work. My only working theory is that I’m targeting the wrong selector – failing that because my jQuery for the MixitUp is within the template part it’s getting loaded before and causing some sort of initialisation issue?
Getting API Data to show on a webpage with Javascript
I’m trying to get data from https://wttr.in/?format=j1 to show on a webpage. I’m very new to Javascript so I hoped this would be easy but I’m struggling to get it to work, what am I doing wrong?.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="temp"></p>
</body>
<script>
const api_url = "https://wttr.in/?format=j1";
async function getWeather() {
const response = await fetch(api_url);
const data = await response.json();
const weather = data.results[0].current_condition[0];
let { temp } = weather.temp_C;
document.getElementById("temp").href = "temp:" + temp;
getWeather();
</script>
</html>
Automatic HTML redirect posting parameters and re-using them again (NOOB ALERT)
I have a few things I want to do programatically… and to make it more difficult it must happen in HTML (javascript can be used)..
1.) If I go to page1.com, I want to pick up the current page’s URL (page1.com) as a “variable/parameter” and automatically redirect and post the URL to a new page – www.page2.com (it must be possible to pick up the current URL with a javascript?)
So, www.page1.com automatically redirects to page2.com posting “page1.com” to page2.com
then…
2.) On page2.com I want to pick up and display “you have been redirected here from page1.com” – page1.com being the variable/parameter posted from the initial page.
but…
3.) I preferably don’t want to use a URL encode as then it’s easy to manipulate the input if the redirect is “page2.com?url=page1.com” – THUS the reason I want to post page1.com to page2.com – as I understand it the post will not display in the URL but in the page itself?
Hope this makes sense?
How to apply a style with JS on the mobile menu?
On my Drupal 9 website, I activated the Olivero default theme. Here is a demonstration :
https://tugboat-aqrmztryfqsezpvnghut1cszck2wwasr.tugboatqa.com/
I added to my subtheme, the following code :
script.js :
(function ($, Drupal, window, document) {
$(document).ready(function () {
window.addEventListener("scroll", function() {
if (document.body.scrollTop > 1 || document.documentElement.scrollTop > 1) {
document.getElementById("site-header__inner").style.boxShadow = "-36px 1px 36px rgb(0 0 0 / 8%)";
} else {
document.getElementById("site-header__inner").style.boxShadow = "none";
}
});
});
})(jQuery, Drupal, this, this.document);
The problem is that the style is applied to the mobile menu and the desktop menu. How does this code only apply to the mobile menu ?
When I inspect the page, I find this in css, but I don’t know how to use it for the solution of my question :
@media (min-width: 75rem)
body:not(.is-always-mobile-nav).toolbar-horizontal.toolbar-fixed.toolbar-tray-open .site-header__fixable.is-fixed {
top: 0.4375rem;
}
Inconsistent animation times between each point in spline chart
I have the following points in my spline chart:
I am experiencing an issue where each point takes an inconsistent amount of time to render.
As an example of the problem, if I have set the animation duration to 1 minute, I would like each line to take 25 seconds to render. However, this is not the case. How can I overcome this issue?
sql add “n” row with values
I have code below.
When I click the button, the new value is named “name+1”
I want to enter these values into the sql database
Bad Sql query:
$sql = "INSERT INTO bb(numer, ID, numerczesci, iloscczesci, przyczyna,
numerfaktury, data, uwagi)
VALUES ('','','$numerczesci','$iloscczesci',
'$przyczyna', '$numerfaktury', '$data', '$uwagi' )";
I don’t know how to declare variables and what sql query to write.
var i =0;
var k =0;
function duplicate() {
var original = document.getElementById('duplic');
var rows = original.parentNode.rows;
i++;
var clone = original.cloneNode(true); // "deep" clone
var InputType = clone.getElementsByTagName("input");
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
k=k+1;
document.getElementById("numerczesci").setAttribute("name", "numerczesci" + k );
document.getElementById("iloscczesci").setAttribute("name", "iloscczesci" + k );
document.getElementById("przyczyna").setAttribute("name", "przyczyna" + k );
document.getElementById("numerfaktury").setAttribute("name", "numerfaktury" + k );
document.getElementById("data").setAttribute("name", "data" + k );
document.getElementById("uwagi").setAttribute("name", "uwagi" + k );
}
<table >
<tr id="duplic"> <td>
<div class="form-group required">
<label for="fldNazwa" class="control-label">numer części/symbol</label>
<input type="text" class="form-control" id="numerczesci" name="numerczesci" required>
</div>
<div class="form-group required">
<label for="fldNazwa" class="control-label">ilość części</label>
<input type="number" class="form-control" id="iloscczesci" name="iloscczesci" value="1" min="1" required>
<br>
<div class="form-group required">
<label for="fldNazwa" class="control-label">przyczyna zwrotu</label>
<select name="przyczyna" required id="przyczyna">
<option disabled selected value> -- wybierz opcję -- </option>
<option value="zlaczesc">część źle zamówiona </option>
<option value="bladdostawcy">błąd dostawcy przy wysyłce </option>
<option value="czescuszkodzona">część uszkodzona podczas transportu lub wadliwa</option>
</select>
</div>
<div class="form-group required">
<label for="fldNazwa" class="control-label">numer faktury</label>
<input type="text" class="form-control" id="numerfaktury" name="numerfaktury" required>
</div>
<div class="form-group ">
<label for="fldNazwa" class="control-label">data wystawienia faktury</label>
<input type="date" class="form-control" id="data" name="data">
</div>
</div>
<div class="form-group ">
<label for="fldNazwa" class="control-label">uwagi</label>
<textarea class="form-control" id="uwagi" name="uwagi"></textarea>
</div>
<br> <br>
</td>
<td>
</td>
</tr>
</table>
<button id="addmore" onclick="duplicate()">Dodaj Towar</button>
<br><br>
how to make a horizontal animation that works synchronously with the scroll? (JS)
Can you please tell me how to make a horizontal animation that works synchronously with the scroll?
I made a sample, but there is a drawback – the event has a start and end point, and I want to make a permanent animation:
const targetTx = document.querySelector('h1');
function animateTx() {
if (document.documentElement.scrollTop > 50) {
targetTx.classList.add('active');
} else {
targetTx.classList.remove('active');
}
}
window.onscroll = function() {animateTx()};
section {
height: 600px;
border-bottom: solid 1px #000;
overflow: hidden;
}
h1 {
display: block;
font-size: 10rem;
color: #999;
white-space: nowrap;
transition: 0.5s;
}
h1.active {
margin-left: -50%;
transition: 0.5s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<section>
<h1>TEST TEXT</h1>
</section>
<section></section>
</body>
</html>
Thank you in advance!
how to import a react 3rd party library into the project (the library uses module.exports but in react we use import syntax)
how to import a react 3rd party library into the project (the library uses module.exports but in react we use import syntax)
Library which i want to use inside my react project is mentioned below : –
Can u please get some help !!
