I run the project and I get this error in the browser, what should I do?
What are the problems in the code?
enter image description here
Category: javascript
Category Added in a WPeMatico Campaign
Show each div in HTMl collection for 1 sec then hide it
I have 10 divs inside a container.
I want to show 1 div for 1 second the remove it and show notthing for 1 sec then show next div for 1 sec and so on.
Right now I started with all divs having a class of hide which is display:none in CSS.
And in JS this is what I have for the moment:
function showOneAtTheTime() {
myShapes(); // function which creating the 10 divs
let all = document.getElementsByClassName('boxes'); //getting the html collection
for (let i = 0; i <= all.length; i++) {
const boxSelect = all[i]; // each div
/*HERE I thought I add the code to show 1 div for 1 second the blank for 1 sec
then show next div*/
}
}
Blank page after wrapping components in react-router v6
I am testing out react-router-dom v6 but facing a constant issue that after wrapping everything up in react-router it’s returning a blank page. I’ve tried with different components but the output is the same.
Navbar.js
import React from 'react'
import * as FaIcons from 'react-icons/fa'
import { Link } from 'react-router-dom'
function Navbar() {
return (
<div className='navbar'>
<Link to='/' className='menu-bars'>
<FaIcons.FaAirbnb />
</Link>
</div>
)
}
export default Navbar
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
App.js
import { Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
export default function App() {
return (
<>
<Router>
<Routes>
<Route exact path='/' element={<Navbar />} />
</Routes>
</Router>
</>
)
}
How to pass javascript array of dictionary to flask
I have an array of dictionaries in javascript that I want to send as payload to a POST request to flask.
However, the array always gets sent empty.
Javascript:
{% for department in departments %}
var department_id = "{{ department.id }}"
var cardgroup = $("#cardgroups_{{ department.id }}").val();
var doorgroup = $("#doorgroups_{{ department.id }}").val();
data.push({
department_id: department_id,
cardgroup_id: cardgroup,
doorgroup_id: doorgroup
});
{% endfor %}
$.post("data/save-office/"+office, data={data: data}, function (data) {
if (data['error']) {
alert(data['error']);
}
else
if (data['success']) {
load_table();
}
});
python:
@app.post('/data/save-office/<office>')
def save_office(office):
departments = request.args.getlist('data[]'). # departments = []
I tried to change departments to request.args.getlist('data') but it returned the same thing.
I also tried to use AJAX instead but it was basically the same thing.
React – useState and mapping
I am going to do my best to try and articulate this – so hopefully this is clear. I am currently building a “Quote Builder” in React, which I am learning with as we go.
I am using the WPAPI to hook into the data within WordPress, which also uses ACF to gather further data – which I have done (screenshot attached of a sample bit of data I am calling).
I then have an OnChange function which grabs the data (from the screenshot), which will then need to update the state – which will then update the page itself:
const quoteTypeChange = async (e) => {
e.preventDefault();
const optionValue = e.target.value;
try {
await wp.quoteType().id(optionValue).then((data) => {
const quoteTypeDetails = data;
// useState update here //
}).catch((error) => {
// Error //
});
} catch (error) {
// Error //
}
}
Within the “Quote Builder” it will display the data into a table – which I have build the front-end of it and its using the following components:
<QuotePhaseTitle title="Title goes here" style="primary" />
and:
<QuoteComponentRow inclusion="Inclusion goes here" deDesktop="2" deMobile="2" deWireframe="2" digital="2" notes="Test notes" />
What I want to be able to do is using the data from the screenshot, map out the data and structure it using those components. From the data the “phase” element will use “QuotePhaseTitle” component and the “quote” will use the “QuoteComponentRow” component, but those can exist in any order and repeated however often that is needed – but they have to go in the order that appears in the data flow – if that makes sense.
How would you go about doing this?
Click and hold reveal and release to hide with timer
sorry for the stupid question, but I couldn’t really find an answer. For an oTree project, I need to create a button (clickbutton) where if clicked AND held, a box of information is revealed (effectbox) and if released the box disappears. I also want to record the time spent “holding” the button, and I can imagine that the participant will click and “hold” multiple times, but I only need the total time spent “holding” the button regardless of how many times it has been clicked. This is what I have so far:
var showBox = document.querySelectorAll(".clickbutton");
var effectbox = document.querySelectorAll(".effectbox");
showBox.forEach(function (el) {
el.addEventListener("click", function () {
effectbox.forEach(function (e) {
e.classList.remove("show");
});
var id = el.getAttribute("data-id");
document.getElementById(id).classList.add("show");
});
});
Thanks in advance!
Single regex test will only pass on first form submission
I have just worked on a basic javascript file to parse html form data on the front-end before it gets submitted. It is almost working as I want, except for one instance of regex.test(). My code is as follows:
const first_name = document.getElementById("fname"); //text field
const last_name = document.getElementById("sname"); //text field
const email = document.getElementById("email"); //email field
const pass = document.getElementById("password"); //password field
const conf_pass = document.getElementById("cpassword"); //password field
const school = document.getElementById("school"); //text field
const reg_str = /^[a-z-]+$/i;
const reg_school = /^[a-zs]+$/i;
const reg_email = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
const reg_pass = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[A-Za-zd]{8,}$/;
let error = "";
function validate() {
if(!reg_str.test(first_name.value)) {
error = "Please ensure that your first name only includes letters and hyphens.";
} else if(!reg_str.test(last_name.value)) {
error = "Please ensure that your last name only includes letters and hyphens.";
} else if(!reg_email.test(email.value)) {
error = "Check your email is of valid format.";
} else if(pass.value.length < 8) {
error = "Please choose a password that is at least 8 characters long.";
} else if(!reg_pass.test(pass.value)) {
error = "Please ensure password contains at least one uppercase, one lowercase and one digit.";
} else if(pass.value != conf_pass.value) {
error = "Passwords do not match, please check and try again.";
} else if(!reg_school.test(school.value)) {
error = "Please ensure that your school name only includes letters and spaces.";
}
if(error != "") {
alert(error);
return false;
} else {
return true;
}
}
Everything is working as expected except for the !reg_school.test(school.value) conditional. It will pass successfully on the first form submission as required, but if it fails once then it will continue to fail indefinitely. Originally it was using the reg_str regex, resulting in the same error (although only for the school, the names are working fine). I have seen similar queries around, but they always come back to the global tag in regex, which I have not used. What can I do to fix this?
Append div 10 times each time button clicked using javascript
This is my code:
$(document).ready(function () {
$('<button class="btn more">View More</button>')
.appendTo(".listing-item-container")
.click(function() {
$(this).closest(".listing-item-container").removeClass("collapsed");
});
$('<button class="btn less">View Less</button>')
.appendTo(".listing-item-container")
.click(function() {
$(this).closest(".listing-item-container").addClass("collapsed");
});
});
.listing-item-container.collapsed > :nth-of-type(n+3) {
display:none;
}
.listing-item-container > .more {
display:none;
}
.listing-item-container > .less {
display:block;
}
.listing-item-container.collapsed > .more {
display:block;
}
.listing-item-container.collapsed > .less {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="listing-item-container collapsed">
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div><div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<!-- 100 more listing-item divs present here -->
</div>
In above code when I click view more, it will display all remaining ‘listing item’ div and when I click view less, all divs are collapsed and display only 2 divs.
My expected output is, when I click view more it should only display next 2 ‘listing item’ div and view more button. Again If I click view more, it should display next 2 ‘listing item’ div and view more button. This should continue for all 100 more ‘listing item’ div. In the end it should display view less button. When I click view less button, each time it should collapse last 2 ‘listing item’ div.
How can I modify my code to get the expected output?
How to submit a form on 2 different urls one after the other?
I have a form which takes some settings as input and contains 2 buttons, one to save the form and another one to save and execute the settings.
<form method="post" action="/settings/{{id}}/save">
<!-- input fields -->
<button type="submit">Save</button>
<button type="submit" onclick="saveAndExecute(this)">Save and Execute</button>
</form>
I referred from this answer: https://stackoverflow.com/a/8731806, and added saveAndExecute() function to submit form to different urls by updating the action of the form.
function saveAndExecute(button) {
const form = button.closest("form"); // To get the form object
form.submit(); // Save the form (save url)
form.action = "/settings/{{id}}/execute"; // Updating the form action url
form.submit(); // Execute the setting
form.action = "/settings/{{id}}/save"; // Update the action url back to original url
}
This is working fine for me, but I’m not sure if this is the correct way to submit form multiple times. Please correct me if I’m wrong, or if there are any other improvements?
Also, after submitting through Save and Execute, my page url also changes (/execute/ is appended after the page url). How can I fix this?
P.S. I’m not experienced in frontend technologies.
P.P.S. I’m not using any frontend framework/library other than jQuery.
What does thedot mean in JS?
let a = {}
let b = a
a.v = 1
b.v = 2
console.log(a.v)
I don’t understand the use of the dot here.
Do you know what that means ?
I tried to console log it
Loading an interactive Plotly graph at a click of a button in Django
I am working on a stock screener project using Django, Pandas and Plotly. One of the pages is the user’s watchlist where certain stats get displayed for each stock (one HTML table row per stock). This HTML table gets generated in the “watchlist” view by converting a Pandas DataFrame into html using the “to_html” method (with escape=False).
Each row of the HTML table has a “View graph” button which opens an interactive Plotly graph for the relevant stock. The graph is generated based on the results of the calculations made in the “watchlist” view, and is represented by an html string that gets sent to the “watchlist” template as part of the context.
At the moment I am loading all the stock graphs below the HTML table each time the “watchlist” page gets loaded, but initially the graphs remain hidden with css. Each graph has an id in the dataset that allows me to “unhide” it with JavaScript when someone clicks the matching button with the same id in the table.
However, loading all the graphs at once when the “watchlist” page is being loaded takes a lot of time, and I am trying to think of for a solution that would make the process faster and that would be optimal architecturally. The number of stocks (and matching graphs) in a user’s watchlist can be up to 50-100.
My understanding is that potential options are:
-
create a “graph” template and view, and then use each “View graph” button to direct the user to the “graph” template that would display the relevant graph. However, I am not sure whether it is possible to pass a graph represented as an html string to the “graph” view.
-
create a separate HTML file for each graph at the point when calculations are being made in the “watchlist” view, then link each “View graph” button to the relevant HTML file. However, I am not sure where these HTML files need to go (especially after deployment) and how I could clean them up on a regular basis (as each graph would only be needed once).
-
load each graph on the “watchlist” page asynchronously when the matching “View graph” button gets clicked (as opposed to loading all the graphs at once when the page loads initially). I am using Vanilla JavaScript for the project’s front end, and was wondering if this can be implemented without introducing React, JQuery etc.
I apologise if there is an obvious solution here, but I have not worked with Django for too long, and would appreciate advice on how to handle this before I go down the rabbit hole of learning new tools that may or may not be optimal for this particular case.
Thank you so much!
How to run link which is in terminal of vs code?
My problem is that I am unable to run http://127.0.0.1:5001/ this link via terminal
need help 🙁
- Serving Flask app ‘main’ (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: on
- Restarting with stat
- Debugger is active!
- Debugger PIN: 604-307-579
- Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
How to add and remove an icon with jQuery
I am trying to make a toggle button work to add and remove a featured star. I am doing this in jQuery. Below I am including the HTML, jQuery and CSS Code
//Toggling Favorites on and off
$("#flexSwitchCheckChecked, label[for='flexSwitchCheckChecked']").click(function() {
var toggleText = $(this).text() == 'Hide Featured' ? 'Show Featured' : 'Hide Featured';
$(this).text(toggleText);
if ($('td i.fa-star').hasClass('fa-star')) {
$('td i.fa-star').addClass('hideFeatured')
} else if ($('td i.hideFeatured').hasClass('hideFeatured')) {
$(this).addClass('showFeature')
}
})
//End of Toggling Favorites on and off
<td class="align-middle" data-uw-styling-context="true">
<a class="mx-2 blue-text" href="https://www.facebook.com/BrowardCountyGovernment/" type="button" target="_blank">
<i class="fab fa-2x fa-facebook" aria-hidden="true" data-uw-styling-context="true"></i></a>
<a class="mx-2 light-blue-text" href="https://twitter.com/browardcounty" type="button" target="_blank">
<i class="fab fa-2x fa-twitter" aria-hidden="true" data-uw-styling-context="true"></i></a>
<a class="mx-2 red-text" href="http://https://www.youtube.com/channel/UCkFUpAuNegNExxOKo_5KJ6w/videos" type="button" target="_blank">
<span class="my-auto my-lg-0 fa-layers fa-fw mr-2" data-uw-styling-context="true">
<i class="fab fa-2x fa-youtube" aria-hidden="true" data-uw-styling-context="true"></i>
<i class="fas fa-1x fa-star" style="color:#fbc02d" data-fa-transform="shrink-2 up-8 left-8" aria-hidden="true" data-uw-styling-context="true"></i>
</span></a>
<a class="mx-2 text-secondary" href="https://www.instagram.com/browardcountylife/" type="button" target="_blank">
<i class="fab fa-2x fa-instagram" aria-hidden="true" data-uw-styling-context="true"></i></a>
</td>
.hideFeatured {
display: none;
}
.showFeatured {
display: inline-block;
}
How does Youtube plays video with sound on mobile Safari if Apple block autoplay with sound?
As per Apple documentation autoplay only works if the video is muted. But for some reason on Youtube when I open a video from the homepage, it starts automatically (without touching anything on the screen) with sound. How did Youtube implement this functionality?
Context provider value gets displayed then disappears
I have a mini react application to practice useContext hook, I made a theme context that enables the user to toggle the website’s theme color between black and grey, and it works fine, then I made another context for the current user, the user can navigate to the signup page and enter his name, and when the user clicks signup, a function called userSignup will set the current name to whatever the user entered as a value in the input and it is supposed to be displayed at the top left corner of the navbar. But the problem is, the name gets displayed for less than a second and then disappears.
This is the code of the App.js file:
import React, { createContext, useState, useContext, useEffect, useReducer } from 'react';
import './style.css'
import {
BrowserRouter as Router,
Routes,
Route,
Link
} from "react-router-dom";
import Home from './Home';
import Shop from './Shop';
import Signup from './Signup';
export let themeContext = createContext();
export let currentUser = createContext()
export default function App() {
const [theme, setTheme] = useState('black');
const [user, setUser] = useState();
const userSignUp = (name) => {
setUser(name);
}
return (
<Router>
<themeContext.Provider value={theme}>
<currentUser.Provider value={user}>
<div className="app" style={{ backgroundColor: theme }}>
<nav className='nav-bar' >
<div className="brand">
Hello {user}
</div>
<div className="nav-elements">
<Link to={'/'}>HOME</Link>
<Link to={'/Shop'}>SHOP</Link>
<Link to={'/signup'}>SIGNUP</Link>
</div>
<div className="theme">
<label htmlFor="checkbox-switch" className='text'>toggle theme</label>
<div className="switch">
<input type="checkbox" id='checkbox-switch' onChange={() => setTheme(theme === 'black' ? 'grey' : 'black')} />
<div className="bgrnd">
<label htmlFor="checkbox-switch" className="toggle"></label>
</div>
</div>
</div>
</nav>
</div>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/Shop/' element={<Shop />} />
<Route path='/signup/' element={<Signup userSignUp={userSignUp} />} />
</Routes>
</currentUser.Provider>
</themeContext.Provider>
</Router>
);
}
This is the code for the signup page component:
import React, { useContext,useRef } from 'react';
import { themeContext } from './App';
import { currentUser } from './App';
import './style.css'
export default function Signup({userSignUp}) {
const theme = useContext(themeContext)
const user = useContext(currentUser)
const info = useRef()
return (
<div className="signup" style={{ backgroundColor: theme, color: 'white' }}>
<h1>Hello {user} this is the signup page title</h1>
<p>Hello the is the signup page content</p>
<form action="">
<div>
<label htmlFor="name">
Type your name
<input type="text" id='name' ref={info} />
</label>
</div>
<div>
<label htmlFor="nickname">
Type your nickname
<input type="text" id='nickname' />
</label>
</div>
<input type="submit" value='Sign up' onClick={()=>userSignUp(info.current.value)}/>
</form>
</div>
);
}
And the is the styling code:
body{
padding: 0;
margin: 0;
height: 100vh;
}
html{
font-size: 10px;
}
#root{
width: 100%;
height: 100%;
}
.app{
padding: 7rem;
background-color: black;
}
.nav-bar{
display: flex;
justify-content: space-between;
align-items: center;
color: white;
font-size: 2rem;
}
.nav-elements{
display: flex;}
.nav-elements a{
text-decoration: none;
color: white;
margin: 0 4rem;
}
.bgrnd{
background-color: white;
height: 3rem;
width: 9.5rem;
border-radius: 3rem;
color: wheat;
position: relative;
}
.bgrnd::before{
content: '';
position: absolute;
background-color: gray;
border-radius: 3rem;
height: 3rem;
width: 3rem;
transition: all .2s linear;
}
#checkbox-switch{
opacity: 0;
}
#checkbox-switch:checked + .bgrnd::before{
transform: translateX(6.5rem);
background-color: black;
}
.toggle{
position: absolute;
width: 9.5rem;
height: 3rem;
border-radius: 3rem;
}
.theme{
display: flex;
align-items: center;
justify-content: space-around;
width: 25rem;
}
.theme .text{
font-size: 2.5rem;
margin-top: 1.7rem;
}
p,h1{
font-size: 4rem;
}