I need to execute a function foo() twice and I need a wait interval between the first and the second execution. How can I do this with jQuery?
How to execute a function twice after a period of time with jQuery?
Click on a component to navigate to another page
I am trying to create a page with clickable cards. Each of the cards is a component. So, as a user, I should be able to click on one of these cards and it will send you to a page "CareerPage." However, I am struggling to get the links working for each card. I have tried what I have below. Thank you.
Explore.js (This is the page with all of the cards)
import './Explore.css';
import CareerCard from './components/CareerCard.js';
import CareerPage from '..//Career-Pages/CareerPage';
//<Route exact path="/CareerPage" component={CareerPage} />;
class Explore extends React.Component {
render() {
const clusters = this.props.clusters.map(cluster => {
return <CareerCard cluster={cluster} key={cluster.id} />;
});
return (
<div className="background-explorepage">
<div className="center-background-1">
<div className="textbox-1">
<h1 className="text1">Explore These Careers</h1>
</div>
<div className="textbox-2">
<h1 className="text2">Click On A Career To Learn More</h1>
</div>
<div className="career-box">
<CareerPage // This is not working here
<div className="row1">{clusters}</div>
/>
</div>
</div>
</div>
);
}
}
export default Explore;
CareerCard.js (This defines the career card component)
import Explore from '../Explore';
class CareerCard extends React.Component {
render() {
return <div className="career-card"></div>;
}
}
export default CareerCard;
CareerPage.js (This is the page I want to go to once a card is clicked)
import React from 'react';
import './CareerPage.css';
function CareerPage() {
return (
<div className="background-careerpage">
<div className="center-background-2">
<div className="career-name-div">
<h1 className="career-name">Career Name</h1>
</div>
<div className="career-box-1">
<div className="left-side-div">
<div className="description-div">
<h1 className="description-title">Description</h1>
<div className="description-text-div">
<p className="description-text">
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing
</p>
</div>
</div>
<div className="day-div">
<h1 className="day-title">A Day In The Life</h1>
<div className="day-text-div">
<p className="day-text">
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing
</p>{''}
</div>
</div>
</div>
<div className="right-side-div">
<div className="salary-div">
<h1 className="salary-title">Average Salary</h1>
<div className="salary-text-div">
<p className="salary-text">
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing
</p>
</div>
</div>
<div className="celebrities-div">
<h1 className="celebrities-title">Celebrities</h1>
<div className="celebrities-text-div">
<p className="celebrities-text">
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing
</p>{''}
</div>
</div>
<div className="classes-div">
<h1 className="classes-title">Relevant Classes</h1>
<div className="classes-text-div">
<p className="classes-text">
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing
</p>{''}
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default CareerPage;
Fill container slide-show bug
Well, what i'm trying to do is a slide-show with a overlapping caption when hovering the its container or image. The image must be exact fit to the container box so it won't show the scroll-bar and the border radius is correct. I was able to do it, however there's a bug. When the page is loaded first it's normal, but a flickering happens and the scroll-bar appears, or the inverse (first the scroll-bar is there and then is not). Is there a way to resolve this?
I tested with Chrome and Firefox and both presents the same incorrect behaviour.
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("slide");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
} else if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
@charset "UTF-8";
* {
margin: 0px;
padding: 0px;
}
#header {
background-color: #202020;
height: 120px;
overflow: auto;
}
body {
background-color: #f5f5f5;
}
.navbar li {
display: inline;
margin-left: 50px;
}
.navbar {
font-family: "Roboto Thin";
font-size: 20pt;
color: white;
list-style-type: none;
padding-top: 48px;
margin-left: 400px;
}
#login {
font-size: 14pt;
color: white;
float: right;
padding-top: 57px;
padding-right: 35px;
}
#login li {
display: inline;
margin-left: 10px;
}
.titulo {
font-family: "Roboto Light";
font-size: 45pt;
}
img#mds-modern {
float: left;
padding-top: 15px;
height: 100px;
}
img#mds-logo {
float: left;
height: 120px;
}
div.body {
padding-top: 20px;
}
.carousel-container {
max-width: 773px;
max-height: 509px;
border-radius: 10px;
position: relative;
margin: auto;
overflow: auto;
}
.slide {
display: none;
}
.slide img {
width: 100%;
height: 100%;
}
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
.caption {
height: 50px;
color: rgba(242, 242, 242, 0);
font-size: 20pt;
font-family: "Roboto Thin";
padding-top: 12.5px;
position: absolute;
bottom: 0px;
width: 100%;
text-align: center;
}
.carousel-container:hover .caption {
background: linear-gradient(rgba(0, 0, 0, 0.1), rgba(25, 25, 25, 0.8));
color: #f2f2f2;
transition: background 2s;
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active,
.dot:hover {
background-color: #717171;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
.row::after {
content: "";
display: table;
clear: both;
}
.column {
float: left;
width: 33.33%;
}
@-webkit-keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
@keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
<!DOCTYPE html><html><head lang="pt-br"><meta charset="utf-8"><title>Malucos do Sealp</title><link type="text/css" rel="stylesheet" href="estilos.css"><script language="javascript" src="script.js"></script></head><body><div class="header-container"><nav><header id="header"><img id="mds-logo" src="MDS.png" alt="Escudo MDS"><img id="mds-modern" src="MDS Modern Logo.png" alt="MDS Logo Moderna"><ul class="navbar" id="login"><li>Login</li><li>|</li><li>Seja Um Maluco</li></ul><ul class="navbar"><li>Notícias</li><li>Loja</li><li>História</li><li>Jogadores</li></ul></header></nav></div><div class="body"><div class="carousel-container"><div class="slide fade"><img src="MDS Anúncio.jpg" alt="Anúncio de novos uniformes"><div class="caption"><p>Novo uniforme para a temporada</p></div></div><div class="slide fade"><img src="MDS Produto.jpg" alt="Produto uniforme"><div class="caption"><p>Compre já seu uniforme</p></div></div><div class="slide fade"><img src="MDS Reborn.jpg" alt="Reborn"><div class="caption"><p>MDS REBORN</p></div></div><a class="prev" onclick="plusSlides(-1)">❮</a><a class="next" onclick="plusSlides(1)">❯</a></div><br><div class="row"><div class="column"></div></div></div><!-- The dots --><div style="text-align:center"><span class="dot" onclick="currentSlide(1)"></span><span class="dot" onclick="currentSlide(2)"></span><span class="dot" onclick="currentSlide(3)"></span></div><script>
showSlides(0)</script></div></body></html>
jQuery add target="_blank" for outgoing link
I need some help to create jquery script :)
I have some of link like this on my HTML.
<a href="http://google.com">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>
And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com
). Then add target="_blank"
. and the result will be like this
<a href="http://google.com" target="_blank">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>
Why my IPC communication doesn't work properly?
This's a simple video duration check program built with Electron. However, it doesn't work as expected; I also tried to use Electron IPC communication in others projects, but always fails. I can upload a video successfully and submit it, after that nothings happens, any errors or advices. Debugger shows nothing too. I built a new project from zero and have same issue. Path value is also not showed on console
main.js:
const electron = require('electron'),
app = electron.app,
BrowserWindow = electron.BrowserWindow
const ffmpeg = require('fluent-ffmpeg')
const ipc = require('electron').ipcMain
let mainWindow
app.on('ready', () => {
mainWindow = new BrowserWindow({})
mainWindow.loadFile('./index.html')
})
ipc.on('video:submit', (event, path) => {
ffmpeg.ffprobe(path, (metadata) => {
event.returnValue = metadata.format.duration
})
})
index.html:
<html>
<head>
</head>
<body>
<form id="form">
<h1>Video Info</h1>
<div>
<label>Select a video</label>
<input type="file" accept="video/*" id="input">
</div>
<button type="submit" id="sb">Get info</button>
<div id="result"></div>
</form>
</body>
<script>
require('./renderer.js')
</script>
</html>
renderer.js:
const ipc = require('electron').ipcRenderer,
form = document.querySelector('#form')
let result = document.querySelector('#result')
console.log(path)
form.addEventListener('submit', () => {
const path = document.querySelector('#input').files[0].path
let reply = ipc.sendSync('video:submit', path)
result.innerHTML = 'Video is' + reply + 'seconds!'
})
How to create a dinamically select based on the value selected in the first select with SQlite querying data in flask and javascript?
I am not getting anywhere on this. Any help regarding this would be greatly appreciated!
I am newbie using Flask with Javascript. I have two query's in a render template to show data of two tables (the first named "modulos" and the second named "layouts") using a for loop, it works well.
But now what I want to populate layouts select with the layouts name by querying a SQLite database with the Modulos name a user selects in modulos select.
So far I have the following code:
{% extends 'base.html' %}
{% block contenido %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Seleccion</title>
</head>
<body>
<select class="browser-default" id="modulos" name="modulos">
{% for modulo in modulos %}
<option class="modulos" codigo="{{ modulo['id'] }}" value="{{ modulo['id'] }}"> {{ modulo['nombre'] }} </option>>
{% endfor %}
</select>
<select class="browser-default" id="layouts" name="layouts">
{% for layout in layouts %}
<option class="layouts" codigo="{{ layout['modulo_id'] }}" value="{{ layout['modulo_id'] }}">{{ layout['nombre'] }} </option>
{% endfor %}
</select>
</body>
</html>
{% endblock %}
And I have been trying to it with this javascript code:
I have been guiding me on this: http://myapa.es/code-snippets/selets-dependientes-javascript/
<script>
var id1 = document.querySelectorAll("select.modulos");
var id2 = document.querySelectorAll("select.layouts");
// Add a change event to the id1 element, associated with the change function()
if(id1.addEventListener) { // For most browsers except IE 8 and earlier
id1.addEventListener("change", cambiar);
} else if (id1.attachEvent) { // For IE 8 and earlier
id1.attachEvent("change", cambiar); // attachEvent () is the equivalent method to addEventListener ()
}
// definition of cambiar() Function
function cambiar() {
for (var i = 0; i < id2.options.length; i++)
if(id2.options[i].getAttribute("codigo") == id1.options[id1.selectedIndex].getAttribute("codigo")){
id2.options[i].style.display = "block";
}else{
id2.options[i].style.display = "none";
}
id2.value = "";
}
// call cambiar()
cambiar();
</script>
Why do I get an error with importing React
I am learning React.js and I converted this line into pure JavaScript using Babel's online converter:
const element = <div tabIndex="0"></div>;
became:
"use strict";
import { React } from "react";
var element = React.createElement("div", {
tabIndex: "0"
});
console.log(element)
But when I run it in Webstorm, I get an exception:
import { React } from "react";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1072:16)
at Module._compile (internal/modules/cjs/loader.js:1122:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
Align content to left of viewport vuetify
I'm just getting started with Nuxt.js and Vuetify.js with a simple "Hello World". I expected the text to be left aligned to the viewport but instead it's offset. Decreasing the width of the window to 959px makes the text behave as planned so I imagine there's a breakpoint at work. But I can't find the code for that breakpoint. How do I get "Hello World" to go straight to the left
index.vue
<template>
<div>
<h1>Hello World</h1>
</div>
</template>
<script>
export default {
head () {
return {
title: 'Hello World',
meta: [
// hid is used as unique identifier. Do not use `vmid` for it as it will not work
{ hid: 'description', name: 'description', content: 'My custom description' },
{ hid: 'keywords', name: 'keywords', content: 'My custom description' },
]
}
}
}
</script>
How to make an element move on swipe using vanilla JavaScript
I am trying to make my list items move on swipe using JavaScript, my code for it looks like this:
//Delete List Item on Swipe
document.querySelector("#list").addEventListener("touchmove", e => {
if (e.target.className == "list-item") {
console.log("I am being touched");
e.target.style.position = "relative";
e.target.style.left = e.touches[0].clientX;
console.log(e.touches);
}
});
The console.log works but the element does not change its position and I don't know why is this. This is how I generate the list item in case you need to know it:
//display list of materias
getMaterias() {
const materias = document.querySelectorAll("li");
materias.forEach(current => {
current.remove();
});
let notas;
if (localStorage.getItem("notas") === null) {
notas = [];
} else {
notas = JSON.parse(localStorage.getItem("notas"));
}
notas.forEach(nota => {
const li = document.createElement("li");
li.textContent = `${nota[0]} ${nota[1]}`;
li.className = "list-item";
const a = document.createElement("a");
a.className = "link";
a.innerHTML = '<i class="fas fa-times"></i>';
li.appendChild(a);
const ul = document.querySelector("ul");
ul.appendChild(li);
ui.displayPromedioTotal();
});
}
Cannot create constructor for angular component with a string as param
I have a simple component:
export class PlaintextComponent implements OnInit {
schema: PlaintextTagSchema;
constructor(private _ngZone: NgZone, prompt: string, maxRows: number, maxChars: number) {
this.schema.prompt = prompt;
this.schema.maxRows = maxRows;
this.schema.maxChars = maxChars;
}
ngOnInit() {
}
}
When I try to compile my app using ng serve, I get the error:
component.ts:25:40 - error NG2003: No suitable injection token for parameter 'prompt' of class 'PlaintextComponent'.
Found string
25 constructor(private _ngZone: NgZone, prompt: string, maxRows: number, maxChars: number) {
I've looked all over on the internet for this cryptic error and haven't found anything resembling a fix. It looks like a correct constructor to me, but I'm new to angular/TS and it's highly possible i'm missing something incredibly basic. Thanks in advance for the help.
How do I make the first letter of a string uppercase in JavaScript?
How do I make the first letter of a string uppercase, but not change the case of any of the other letters?
For example:
"this is a test"
->"This is a test"
"the Eiffel Tower"
->"The Eiffel Tower"
"/index.html"
->"/index.html"
React Native TouchableOpacity not working with position absolute
I have a list that shows results matching the user's input. The onPress of the touchableOpacity is not working in this list. This list is positioned absolutely and positioned below its parent view (positioned relative). The only time I can get the onPress to work is when I remove the top:48
style from list and the onPress works for the single element which is directly onTop of the parent.
export default function IndoorForm(props) {
return (
<View style={styles.container}>
<View style={styles.parent}>
<Autocomplete
style={styles.autocomplete}
autoCompleteValues={autoCompleteValues}
selectedLocation={props.getDestination}
></Autocomplete>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignSelf: "center",
position: "absolute",
top: Platform.OS === "android" ? 25 + 48 : 0 + 48,
width: Dimensions.get("window").width - 30,
zIndex: 500
},
parent: {
position: "relative",
flex: 1,
borderWidth: 2,
borderColor: "#AA2B45",
height: 48,
backgroundColor: "#fff",
flexDirection: "row",
alignItems: "center",
paddingLeft: 16,
paddingRight: 16,
justifyContent: "space-between"
}
}
export default function AutoComplete(props: AutoCompleteProps) {
const { autoCompleteValues } = props;
return (
<View style={styles.container}>
<FlatList
data={autoCompleteValues}
renderItem={({ item }: { item: POI }) => (
<TouchableOpacity onPress={() => console.log("Haal")} key={item.displayName} style={styles.list}>
<Text style={styles.text}>{item.displayName}</Text>
<Entypo name={"chevron-thin-right"} size={24} color={"#454F63"} />
</TouchableOpacity>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
position: "absolute",
flex: 1,
width: Dimensions.get("window").width - 30,
top: 48,
borderWidth: 2,
borderColor: "#F7F7FA",
backgroundColor: "#F7F7FA",
zIndex: 999
},
list: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 15,
paddingLeft: 10,
paddingBottom: 10,
borderBottomColor: "rgba(120, 132, 158, 0.08)",
borderBottomWidth: 1.4,
zIndex: 999
}
}
Force page reload with html anchors (#) - HTML & JS
Say I'm on a page called /example#myanchor1
where myanchor
is an anchor in the page.
I'd like to link to /example#myanchor2
, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load. The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
Returning a blob always results in empty object
So the below code is the body of a function on the server-side, which I'm later consuming on the client side of the same app:
const fetch = require('node-fetch');
async function fetchImage(url) {
// url: image file url like: http://example.com/img1.png
const res = await fetch(url);
const blob = await res.blob();
console.log(blob);
/* logs a blob successfully
Blob {
I20200316-01:00:19.551(2)? [Symbol(type)]: 'image/jpeg',
I20200316-01:00:19.551(2)? [Symbol(buffer)]: <Buffer ff d8 ff e0 00 10
4a 46 49 46 00 01 01 01 00 60 00 60 00 00 ff e1 0e d2 45 78 69 66 00 00
4d 4d 00 2a 00 00 00 08 00 0c 01 00 00 03 00 00 00 01 03 e8 ... 133125
more bytes>
*/
return blob;
// this however will ALWAYS return {} empty object
}
I tried doing something like return 'Hello Bros!'
just for my sanity and it gets consumed properly.
It's just the blob will not return no matter what.
I'm basically trying to proxy a call on the server side to fetch some images that I can display on my app.
Since the comments asked for the client-side code that uses this function, I'm just trying to do something like this:
async function getImageBlob(url) {
const res = await fetchImage(url);
console.log(res, 'response which is always {} instead of my precious blob');
}
More details: if I can just get the blob, then the real use-case here is that I'm passing it to a 3rd party library that displays the blob as image.
The full longer version
server
Meteor.methods({
async 'products.fetchImage'(url) {
check(url, String);
const res = await fetch(url);
const blob = await res.blob();
console.log(blob, '!!!server blob!!!'); // logs just fine
return blob;
}
})
client
// image uploader
import vueFilePond, { setOptions } from 'vue-filepond';
setOptions({
server: {
// initialize image uploader with images already stored on the server
load: async (source, load) => {
// source: 'http://example.com/img1.png'
const response = await meteorCall('products.fetchImage', source);
console.log('blob?', response); // logs {}
load(response);
},
},
});
const FilePond = vueFilePond();
Scroll one div to trigger another div to scroll at a different speed with jQuery
I have two scrollable divs, div A and div B.
I'd like that when I scroll div A, div B also scrolls in the same direction but more slowly. I'd also like to be able to scroll div B independently while hovering over it.
I've worked out a solution in jquery, as shown in this fiddle: https://jsfiddle.net/j4nuxq97/11/
var position = $(window).scrollTop();
$(".div-a").scroll(function() {
var scroll = $(".div-a").scrollTop();
if (scroll > position) {
var y = $(".div-b").scrollTop();
$(".div-b").scrollTop(y + 20);
} else {
var y = $(".div-b").scrollTop();
$(".div-b").scrollTop(y - 20);
}
position = scroll;
});
div{
height:200px;
width:100px;
overflow:scroll;
display:inline-block;
margin-left:30px;
scroll-behavior: smooth;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="div-a">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br></div><div class="div-b">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br></div>
the problem is that it's a really unpleasant animation:
div B always moves after div A has, rather than at the same time
the animation is really jerky, and the amount moved varies based on the speed at which div A is scrolled
Can anyone recommend the best way to make this feel smoother, and closer to the way the animation on this site feels: http://spassky-fischer.fr/
Thanks in advance.
route is not hitting nested controller
I have this structure in my app using Express and Node.js
//index.js
const authRoutes = require('./auth);
app.use('/auth', authRoutes(logger));
//auth.js
const authController = require('./authController);
const express = require('express');
const router = express.Router();
module.exports = function(logger)
{
return function(req,res,next){
router.post('/signup',authController.signup(logger));
return router
}
//authController.js
const signup = (logger) =>
{
logger.info('outside');
return function(req,res,next)
{
logger.info('inside');
}
}
module.exports = {
signup
}
The code prints outside but not inside what's the problem? and if the variable passed by app.use is the problem is it efficient if i required the logger module when I need it
Javascript Form Validation, multiple functions on a single button not working correctly
I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
How do I add HTML attributes to an array using Javascript
I am trying to add attributes from three HTML elements to an array.
Here is some sample HTML:
<p x="30">Paragraph 1</p>
<p x="50">Paragraph 2</p>
<p x="100">Paragraph 3</p>
Here is the Javascript that has gotten me closest to the results I am looking for:
const paragraphs = document.querySelectorAll(`p`);
let i;
for (i = 0; i < paragraphs.length; i++) {
let dataSetOne = paragraphs[i].getAttribute('x');
let dataSetOneArray = Array.from(dataSetOne);
}
When I console.log(dataSetOne), I get "30""50""100", which is what I hoped for.
When I try to add these attributes to an array using Array.from(dataSetOne), I end up with three arrays that look like this: Array(1) [ "3", "0" ]; Array(2) [ "5", "0" ] Array(3) [ "1", "0", "0" ].
The array I am looking for is this: Array ["30", "50", "100"]
I have tried a few other functions, but none of these are getting me any closer to the result I am looking for.
This is not for a specific project. I am trying to advance my understanding of arrays and object-oriented programming.
Thanks in advance for your help.
CORS Error: “requests are only supported for protocol schemes: http…” etc
I am trying to run a simple application. I have an Express backend which returns a JSON string when visited at localhost:4201/ticker
. When I run the server and make a request to this link from my Angular Service over http
, I get the following error:
XMLHttpRequest cannot load localhost:4201/ticker. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I read the following article: Understanding and Using CORS and as stated, used the cors
module with my express server. However, I am still getting the error as given above. Part of code is given below:
Server code:
private constructor(baseUrl: string, port: number) {
this._baseUrl = baseUrl;
this._port = port;
this._express = Express();
this._express.use(Cors());
this._handlers = {};
this._hInstance = new Handlers();
this.initHandlers();
this.initExpress();
}
private initHandlers(): void {
// define all the routes here and map to handlers
this._handlers['ticker'] = this._hInstance.ticker;
}
private initExpress(): void {
Object.keys(this._handlers)
.forEach((key) => {
this._express.route(this._url(key))
.get(this._handlers[key]);
});
}
private _url(k: string): string {
return '/' + k;
}
Here is the handler function:
ticker(req: Request, res: Response): void {
Handlers._poloniex
.getTicker()
.then((d) => {
return Filters.tickerFilter(d, Handlers._poloniex.getBases());
})
.then((fdata) => {
//res.header('Access-Control-Allow-Origin', "*");
//res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Content-Type', 'application/json');
res.send(JSON.stringify(fdata));
})
.catch((err) => {
this._logger.log([
'Error: ' + err.toString(),
'File: ' + 'handlers.class.ts',
'Method: ' + 'ticker'
], true);
});
}
Here is my Angular Service:
export class LiveTickerService {
private _baseUrl: string;
private _endpoints: {[key:string]: string};
constructor(
private _http: Http
) {
this._baseUrl = 'localhost:4201/';
this._endpoints = {
'ticker': 'ticker'
};
}
getTickerData(): Observable<Response> {
return this._http.get(this._baseUrl + this._endpoints['ticker'])
.map(resp => resp.json())
}
}
Here is how I am using my Service:
getTicker() {
let a = new Array<{[key: string]: any}>();
this._tickerService.getTickerData()
.subscribe(
data => {
let parsed = JSON.parse(JSON.stringify(data));
Object.keys(parsed)
.forEach((k) => {
a.push({k: parsed[k]});
});
this.data = a;
},
error => console.log(error.toString()),
() => console.log('Finished fetching ticker data')
);
return this.data;
}
Running multiple instance of Node. Facebook Texas Hold'em game
I've been designing a Facebook multiplayer game that allows people to play Texas Hold'em poker in real time. I have nearly finished both the front-end and the back-end and it has taken me two years of hard work to develope. The game is written in pure Javascript using CSS and HTML to provide the graphics.
I currently have the game engine for one table running in a Node.js instance. My problem is that I need multiple tables running concurrently as well as a lobby/menu system where people can pick their table.
As Javascript is single threaded by design and I have promises and blocking code in my design I either need to run multiple instances of node on the same server (one node instance per table) or I need to use clustering or maybe workerthreads.
Does anyone have any ideas or opinions on the route I should go?