I am trying to get animation as this website has, content is smoothly fading into the viewport as the user scroll. Can anyone please guide me on how to achieve a similar effect in react js?
Category: javascript
Category Added in a WPeMatico Campaign
Vue 3/Quasar: Handling opening and closing of modals
I have two modals:
One is a Sign Up modal which takes in information of an existing user. Another modal which allows an existing user to login.
The only way to get to the Login modal is through the Signup modal.
But what I would like to do is, if the use wants to open the Login, I would like to close the Sign up modal first.
Right now that seems impossible with my setup. With the code below (nextTick), it does not work and closes both modals… despite there being a unique v-model for each modal.
Sign up Modal
<template>
<AVModal
:title="$t('signup.create_an_account')"
:button-text="$t('signup.button_text')"
classes="hide-icon q-mt-sm"
modal-style="width: 350px"
v-model="modal"
>
<q-form
@submit="signUp(user)"
class="row column fitq-gutter-md q-gutter-md"
>
<q-input
outlined
v-model="signup_user.username"
:label="$t('signup.name')"
>
<template v-slot:append>
<q-icon name="person" color="grey" />
</template>
</q-input>
<q-input
outlined
v-model="signup_user.email"
type="email"
:label="$t('signup.email')"
>
<template v-slot:append>
<q-icon name="email" color="grey" />
</template>
</q-input>
<q-input
outlined
v-model="signup_user.password"
type="password"
:label="$t('signup.password')"
>
<template v-slot:append>
<q-icon name="lock" color="grey" />
</template>
</q-input>
<q-checkbox
v-model="signup_user.privacy_policy"
color="secondary"
:label="$t('signup.privacy_policy')"
/>
<q-checkbox
v-model="signup_user.newsletter"
color="secondary"
:label="$t('signup.newsletter')"
/>
<q-btn color="primary" class="q-py-sm" type="submit">{{
$t("signup.get_started")
}}</q-btn>
</q-form>
<div class="row q-my-sm q-mt-md fill">
<AVLoginModal @on-open="handleOpen" />
</div>
<!-- <AVSeperator text="or" /> -->
<!-- <AVSocialMediaButtons class="q-mt-md" /> -->
</AVModal>
</template>
<script setup>
import { ref, nextTick } from "vue";
import AVModal from "../atoms/AVModal.vue";
// import AVSeperator from "../atoms/AVSeperator.vue";
// import AVSocialMediaButtons from "../atoms/AVSocialMediaButtons.vue";
import AVLoginModal from "./LoginModal.vue";
import { useAuth } from "../../composables/useAuth";
const modal = ref(false);
const handleOpen = () => {
nextTick(() => (modal.value = false));
};
const { signUp, signup_user } = useAuth();
</script>
Login Modal:
<template>
<AVModal
:title="$t('login.welcome_back')"
:button-text="$t('signup.login_instead')"
classes="hide-icon q-mt-sm fit"
color="blue"
modal-style="width: 350px"
v-model="modal"
@on-open="emit('on-open')"
>
<q-form
@submit="login(login_user)"
class="row column fitq-gutter-md q-gutter-md"
>
<q-input
outlined
v-model="login_user.email"
type="email"
:label="$t('signup.email')"
>
<template v-slot:append>
<q-icon name="email" color="grey" />
</template>
</q-input>
<q-input
outlined
v-model="login_user.password"
type="password"
:label="$t('signup.password')"
>
<template v-slot:append>
<q-icon name="lock" color="grey" />
</template>
</q-input>
<q-btn color="primary" class="q-py-sm" type="submit">{{
$t("login.login")
}}</q-btn>
</q-form>
<!-- <AVSeperator text="or" class="q-my-md" /> -->
<!-- <AVSocialMediaButtons class="q-mt-md" /> -->
</AVModal>
</template>
<script setup>
import { ref, defineEmits } from "vue";
import { useAuth } from "../../composables/useAuth";
import AVModal from "../atoms/AVModal.vue";
// import AVSeperator from "../atoms/AVSeperator.vue";
// import AVSocialMediaButtons from "../atoms/AVSocialMediaButtons.vue";
const modal = ref(false);
const emit = defineEmits(["on-open"]);
const { login_user, login } = useAuth();
</script>
Maybe my design is bad? Is there a more conventional way of creating modals in Quasar?
Dynamic Chart on Popover Error – Cannot Acquire Context
I am trying to create a chart js popover but I am getting the error:
Failed to create chart: can’t acquire context from the given item
I think that this is probably happening because the canvas tag is created dynamically, but I am not sure how to fix it. Any ideas? This is the js code I am using:
$(function() {
$('[data-toggle="popover"]').popover({
html: true,
content: '<canvas id="myChart" width="400" height="400"></canvas>',
}).on('shown.bs.popover', function() {
const myChart = new Chart("#myChart", {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
},
// Configuration options go here
options: {}
});
});
How to make [i] dynamic using jquery?
I have a list there is an array in each list, Now I’m trying to make array [i] dynamic this is not working. How to solve it?
My Code:-
for (let i = 0; i < result.result.length; i++) {
$.each(result.result[i].services, function(key, value) {
serviceList += `<li>${value.name}</li>`;
});
}
ThankYou for your support!
What’s the difference between returning a funcition in an if statement and placing the function body in an if statement?
I realized that this code
function(todo) {
if(!todo) { return }
// some stuff here
}
and this code
function(todo) {
if(todo) {
//some stuff here
}
}
gets you the same result. When the function is called, if the todo argument is truthy, then the “some stuff” gets executed. Is there any diference between these 2 approaches?
Looping though childNodes and deleting all leaves one entry not deleted [duplicate]
I have a function that iterates all options returned from an API fetch, creates a p tag for each, and appends them all to a parent div called options
textOptions.forEach((text) => {
let newText = document.createElement('p')
newText.innerHTML = text
newText.addEventListener('click', () => {
replaceSelectedText(newText.innerHTML, range)
handleCloseMenu()
})
options.appendChild(newText)
})
when the handleCloseMenu() function is executed, it is to check if the div options has any children and if so, remove them all, so that the next API call cacn return a fresh set of children.
const handleCloseMenu = () => {
menu.style.display = 'none'
if (options.hasChildNodes()) {
options.childNodes.forEach((child) => {
child.remove()
})
}
console.log('OPTIONS CHILDREN', options.childNodes)
}
after the loop is done in my console.log I can see it has not deleted one of the children, it always leaves the second child. I also see it sitting there in my options during the next API call. Am I doing something incorrectly? I know I am of course but some info on what the problem is would be greatly appreciated
Problem getting value in a form with Javascript
I’m in my first step with Javascript so maybe the solution is quite obvious but I can’t figure out. I need to modify a stamp in Adobe. When the user insert this stamp, a Javascript form appear. There is already a group of radiobutton (in the code above, “Recommandation”). What I need to do is add another group of radiobutton (in the code above, “NatChoix”). I can’t get the value of which radiobutton was check. “dialogConformiteFR.NatChoix” return nothing. By doing some test, I realize that (results[“rNat1”]), (results[“rNat2”]) and (results[“rNat3”]) never return true when it’s checked on the form.
Hope I’m being enough clear, if not let me know.
This is not the complete code since there is a lot more to it, I just kept the radiobutton part.
(Sorry I had difficulty putting my code snippet …there is always an error about “not properly formatted as code” and I have been trying to post that for 30 minutes! If someone could tell me how to post my code, I could repost it correctly! You will find the code in image 1 and 3. Sorry again for that… newbie here!!)
Thank you !
(Blue)Working radio button, (Purple) the new one not working
Image change upon collision detection in HTML canvas
I am working on a simple game using HTML canvas and JavaScript.
The canvas is as follows:
The canvas part
When the colored ball hits the sides of the image (img 1 and 2 in the above picture), its color will change randomly.
Now, I further want to add a function to it. What I want is that when the colored ball hits the side of the image, I want to change img 1 and 2. How can I do that in my code? I have done some research here and on YouTube but still have no idea. My code is as follows:
var canvas = document.getElementById("canvas_bb84_1");
canvas.width = 1000;
var c = canvas.getContext("2d");
//Draw the image to the canvas
var x = 220;
var radius = 15;
var color = "#0095DD";
function draw() {
c.drawImage(p_fil, 100, 30, 100, 100); //img1
c.drawImage(p_fil_flip, 810, 30, 100, 100); //img2
c.drawImage(p_det_flip, 10, 30, 100, 100);
c.drawImage(p_det, 900, 30, 100, 100);
//Draw the ball
c.beginPath();
c.arc(x, 80, radius, 0, Math.PI * 2, false);
c.fillStyle = color;
c.fill();
c.closePath();
}
//Update the animation of the ball and collision detection
var dx = 4;
function update() {
if (x + radius > 820 || x - radius < 190) {
dx = -dx;
color = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}
x += dx;
}
//Initialize the images
var p_det = new Image();
var p_det_flip = new Image();
var p_fil = new Image();
var p_fil_flip = new Image();
//Animate
function animate() {
p_det.src = "photon_detector.jpg";
p_det_flip.src = "photon_detector_flip.jpg"
p_fil.src = "p_filter_02.jpg";
p_fil_flip.src = "p_filter_02_flip.jpg";
window.requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
draw();
update();
}
animate();
Why does VS code say there is an error with my object property?
I was testing some code that utilizes objects in TypeScript and noticed that my IDE’s IntelliSense was throwing an error for a new property I was trying to add. It states that the property “text” does not exist, here is my code:
// create new object
var thing : Object = new Object();
// Do things
thing.text = "This is a test.";
console.log(thing.text);
// dereference the object
thing = null;
The error is highlighted on the line(s):
thing.text = "This is a test.";
console.log(thing.text);
Why does VS code list this as an error when this is perfectly acceptable code and behavior in JavaScript? Here is the error screenshot from my editor:
Error
Vanta.js not reloading after GSAP & Barba JS transition
Ok so I got a Vanta.js background running in my <main> which looks awesome. Then I introduced a page transition using Barba and GSAP for animations, which are working fine too. But after going back to my index I found that VantaJS isn’t loading again. There are very few questions about Barba and even less answered correctly.
Here’s what I’ve tried until now:
- Use
window.onloadwithappendChildto add the vanta libraries each time. - Use Barba hooks to reload the libraries on “after” hook.
- Send all scripts to the bottom of my html in correct order.
Here are some SO questions I’ve used as example:
How to reinit custom js files between pages (Barba.js)?
Scripts are not loading after the page transition in Barba.jS
JS content not working after a page transition using Barba.JS
No luck implementing any of these.
I’m open to other transition libraries if you think that Barba is the problem definitely.
Thanks in advance.
Group by month and year is in out of order
This question is an extention of this question here. Underscore js group by each month on each year in single level
The code which i am using is here.
const months = [
'January','February','March','April','May','June','July','August','September','October','November','December'
]
const result = flashMessage.reduce((res:any, item:any) => {
const date = new Date(item.created_at)
const year = date.getFullYear();
const month = months[date.getMonth()];
const existingYear=res[`${month} ${year}`] ||[];
const updated = [...(existingYear[month] || []), item]
const returnItem = {
title:item.title,
user_message:item.user_message,
created_at:item.created_at
};
res[`${month} ${year}`] = [...existingYear,returnItem]
return res
}, {});
The above code is producing expected result but it is in out of order here is the result of the above code.
[![enter image description here][1]][1]
I want the result is in order. The order which i wanted is shown below.
March 2022
February 2022
January 2022
March 2021
February 2021
January 2021
So on how can i do that?
[1]: https://i.stack.imgur.com/BS9ZS.png
Select multiple dates in the mutiple date selelect picker
Im using laravel. I have saved multiple dates using multiple date selector. so now i need to select those saved values in that date picked when loading screen again.
my date picker created like this.
<input type="text" id="closed_dates" name="closed_dates" class="form-control date"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<script>
$('#closed_dates').datepicker({
multidate: true
});
</script>
it has saved value in the database like this format,
03/01/2022,03/02/2022,03/09/2022,03/10/2022,03/11/2022
so when loading my page, values pass from the controller.
i need to select those dates in that date picker on the page load. how can i do it?
MUI ToggleButton set selected background-colour dynamically
const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({
"&.Mui-selected, &.Mui-selected:hover": {
backgroundColor: selectedColor,
}
}));
const FilterTeam = (props) => {
const [view, setView] = useState(1);
const handleChange = (event: any, nextView: any) => {
setView(nextView);
};
return (
<ToggleButtonGroup
orientation="horizontal"
value={view}
exclusive
onChange={handleChange}
>
{ Object.values(teams).map((teamObject: any, index) =>
<StyledToggleButton
key={teamObject.team}
className={classes.toggleButton}
value={teamObject.team}
selectedColor={teamObject.colorTheme}
>
<img className={classes.teamLogo}
alt="team logo" src={teamObject.logo} />
</StyledToggleButton>
)}
</ToggleButtonGroup>
);
}
export default FilterTeam
I keep getting:Warning: React does not recognize the selectedColorprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseselectedcolor instead. If you accidentally passed it from a parent component, remove it from the DOM element.. I have gone over a couple sandbox which implement the same but I am trying it on typescript so I am not sure how it converts.
I have referred to https://codesandbox.io/s/69707814-set-selected-color-of-toggle-button-group-mui-5l5lh?file=/demo.js
Export a Monkey Patch library and Import it into a separate file in Javascript
I’m working in WebDriverIO w/Mocha, and there’s some monkey patches I’ve written to make my code easier to read. Things like:
Object.prototype.findEntries(...arr)for getting a subset of Object.entries(),String.prototype.padding(int), adding spacing to the right of a string,Array.prototype.sortByKey(key)to sort an array of similar objects by the value of a common key, andArray.prototype.last(), the classic.
Since I have many spec files with even more tests, I’d like to have a MonkeyPatchLib.js in my project that I can import into my spec files, so I can call these custom functions when needed:
myTest.js:
import { all } from './MonkeyPatchLib.js' // <- line in question
describe('My First Spec File', async() => {
it('First Test', async() => {
let myArr=[1,2,3]
console.log(myArr.last())
})
})
I’ve screwed around with module.exports=[func1(){...},func2(){...}] to no avail. I’m aware that I can simply create custom classes (a la the solution to this question) and export those, but that would require an annoying refactor of my codebase. How should I format the library, and how would one import said library?
Why is JS redis looping more times after succesful write?
I have the following logic for reading and writing redis state
export async function updateRedis() {
let stateName = 'stateName'
try {
let isSuccess = false
while (!isSuccess) {
try {
await redis
.watch(stateName, function (err) {
if (err) {
logger.error(`Error in watch state: ${err}`)
}
redis.get(stateName, function (err, result) {
if (err) {
logger.error(`Error in get state: ${err}`)
}
let state = JSON.parse(result)
// do some processing
redis.multi()
.set(stateName, JSON.stringify(state))
.exec(function (err, result) {
if (err) {
logger.error(`Error in set state: ${err}`)
}
if (result != null) {
isSuccess = true
}
})
console.log(`isSuccess for ${stateName} `, isSuccess)
})
})
} catch (e) {
logger.error(`Error: ${e}`)
}
}
} catch (e) {
logger.error(`Error: ${e}`)
}
return Promise.resolve(true)
}
This will print out
"isSuccess for stateName false"
"isSuccess for stateName true"
"isSuccess for stateName true"
So after the flag changes to true, it will continue for more loops. Sometimes it does more than just once.
Am I doing something wrong?