Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

survey.js 1.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  1. import { sendEvent } from './events'
  2. function showElement (el) {
  3. el.removeAttribute('hidden')
  4. }
  5. function hideElement (el) {
  6. el.setAttribute('hidden', true)
  7. }
  8. function updateDisplay (form, state) {
  9. Array.from(
  10. form.querySelectorAll(
  11. ['start', 'yes', 'no', 'end']
  12. .map(xstate => '[data-help-' + xstate + ']')
  13. .join(',')
  14. )
  15. )
  16. .forEach(hideElement)
  17. Array.from(form.querySelectorAll('[data-help-' + state + ']'))
  18. .forEach(showElement)
  19. }
  20. function submitForm (form) {
  21. const formData = new FormData(form)
  22. const data = Object.fromEntries(
  23. Array.from(formData.entries())
  24. .map(
  25. ([key, value]) => [
  26. key.replace('survey-', ''),
  27. value || undefined // Convert empty strings to undefined
  28. ]
  29. )
  30. )
  31. return trackEvent(data)
  32. }
  33. function trackEvent ({ token, vote, email, comment }) {
  34. return sendEvent({
  35. type: 'survey',
  36. token, // Honeypot
  37. survey_vote: vote === 'Yes',
  38. survey_comment: comment,
  39. survey_email: email
  40. })
  41. }
  42. export default function survey () {
  43. const form = document.querySelector('.js-survey')
  44. const texts = Array.from(document.querySelectorAll('.js-survey input, .js-survey textarea'))
  45. const votes = Array.from(document.querySelectorAll('.js-survey [type=radio]'))
  46. if (!form || !texts.length || !votes.length) return
  47. form.addEventListener('submit', evt => {
  48. evt.preventDefault()
  49. submitForm(form)
  50. updateDisplay(form, 'end')
  51. })
  52. votes.forEach(voteEl => {
  53. voteEl.addEventListener('change', evt => {
  54. const state = evt.target.value.toLowerCase()
  55. const form = voteEl.closest('form')
  56. submitForm(form)
  57. updateDisplay(form, state)
  58. })
  59. })
  60. // Prevent the site search from overtaking your input
  61. texts.forEach(text => {
  62. text.addEventListener('keydown', evt => {
  63. if (evt.code === 'Slash') evt.stopPropagation()
  64. })
  65. })
  66. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...