JS app refreshing on button submit, cannot figure out why

I am learning JS and have a page done in vanilla JS and HTML and for the life of me cannot figure out why when I hit submit, the page refreshes. Please help! I have double checked the ID for the form that I have the event listener on and it is correct.

// Book Constructor
function Book(title, author, isbn) {
  this.title = title;
  this.author = author;
  this.isbn = isbn;
}

// UI Constructor
function UI() {}

// Event Listeners
document.getElementById('book-form').addEventListener('submit', function(e){
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value

  
  console.log(title, author, isbn);
  e.preventDefault();
});

Caps and Lowercase input that also generates in output

I’ve been trying to put together an input where the text automatically capitalizes the first letter of each word and makes all other letters lowercase for that word. I had some success using that for just making everything lower case after the first letter for the input with this:

 <input type = "text" size="8" name="textfield1" id="textfield1" />

with the javascript being

        document.getElementById('textfield1').addEventListener("keyup",   () => {
  var inputValue = document.getElementById('textfield1')['value']; 
  if (inputValue[0] === ' ') {
      inputValue = '';
    } else if (inputValue) {
      inputValue = inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
    }
    
document.getElementById('textfield1')['value'] = inputValue;
});

I tried adding map(), split(), and join() in various ways based off of lessons I’ve found (I’m learning on my own, no formal training since high school) for use in a string with the console.log methods but I’m confused on how I can apply this to an input. It would take too long to note everything I’ve tried but one thing I did was this:

        document.getElementById('textfield1').addEventListener("keyup",   () => {
  var inputValue = document.getElementById('textfield1')['value']; 
if (inputValue[0] === ' ') {
      inputValue = '';
    } else if (inputValue) {
  input.content = input.content.split(' ').map(function(inputValue) {
      return inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}).join(' ');
    }
    
document.getElementById('textfield1')['value'] = inputValue;
});

I’m not sure what I’m missing here. I’m sure there’s something that I’m not seeing or understanding. I also tried looking to see if there was something similar listed on here or elsewhere in relation to this and inputs but I didn’t see anything specific to what I was looking for.

I want the input to remain the same for what comes up with the output into another box when it gets copied over.

Example of what I’m trying to do is:

input of textfield: heLlo OuT thERe!

output to another textarea with the click of a button: Hello Out There!

CSS style font properly

Im using WordPress and uploaded my font locally.

.MyText {font-family: CustomFont}

Its working properly.

But when the page loads, it shows a flash of the text without my added font.

I tried

.MyText {

font-family: CustomFont;
font-display: block

}

But its still showing a flash of styled text, except the font.

How can i fix that?

‘What did you try and what were you expecting?’ Above

Uploading to aws presigned url leads to connection timeout

I’m using the following code to upload a file to a presigned url s3:

        const fetchResult = await fetch('https://filesamples.com/samples/document/txt/sample3.txt');
        const length = (await fetchResult.arrayBuffer()).byteLength;
        formData.append('file', fetchResult.body, js.url);

        const final = await fetch(js.url, {
            body: formData as any,
            headers: {
                'content-length': length.toString()
            },
            method: 'POST'
        })

However this is getting an error:

<Error><Code>RequestTimeout</Code><Message>Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed.</Message><RequestId>4GEG981FJPY0NGTA</RequestId><HostId>y9w+8E0ZIDDQg9IdH95VmK3cZsorupcC4vhnZTuivvkXQ/+1R2HLsK61BC7B3UnMwMzN92pBcjkeBBKKBztUxA==</HostId></Error>

If I was to upload a straight up string like:

formData.append('file', 'test data, js.url);

and that works without timing out.

When declaring an object using a factory function in a module pattern, I am unable to access an array inside the module

I’m having trouble understanding why I am unable to access the variable ‘gameArr’ when creating an object using the ‘createPlayer’ factory function. When I call ‘player.copyArr()’ inside of the module pattern, it is unable to access ‘gameArr’, but ‘testObj.copyArr()’ is able to.

const createPlayer = (name) => {
  let properties = {
      name,
      copyArr(){
        let newArr = gameArr;
        console.log(newArr)
      }
  }

  return player
}

const game = (() => {
  const gameArr = [1,2,3,4,5]

  let player = createPlayer("Fred")

  let testObj = {
    name: "Bob",
    copyArr(){
      let newArr = gameArr;
      console.log(newArr);
    }
  }

  testObj.copyArr();
  player.copyArr();

  return 
})()

I have already found a way to access ‘gameArr’ by either placing the ‘createPlayer’ factory function inside of the ‘game’ module or by adding parameter to the ‘copyArr(gameArr)’ inside of ‘createPlayer’. But I’m still having trouble understanding why the ‘player’ object was unable to access ‘gameArr’ inside of ‘game’ initially.

Thanks

AJAX Dynamic table using JSON template

I am trying to make a dynamic table in the success part of an AJAX call. Depending on the user’s selections, the table can have totally different field names & data (different queries) from one call to the next. I am attempting to do this using JSON data to supply the field names & data for the different scenarios.

JSON

var fields = { 
                "Customer Name": "cust_nm",
                "Circuit ID": "ckt_id",
                "Speed": "speed",
            };

AJAX

success: function (data) {                      
            for (key in fields) {
                if (fields.hasOwnProperty(key)) {
                    var x = 'data.' + fields[key];
                    var row = '<tr><td>' + key + '</td><td> ' + x + '</td></tr>';
                    $('#circuitDetails').append(row);
                }
            }
        }

As can be seen in the result screenshot below, it is recognizing 'data.' + fields[key] as a string rather legitimate data definition. In this case the data returned would have had 3 fields named cust_nm, ckt_id & speed.

enter image description here

Suggestions on how to accomplish this would be appreciated.

How can I make this js doesn’t affect to my css [closed]

I made some grid CSS for the element inside the <div class="row"> element but somehow it is affected by my JS file. When I delete all the div column in HTML it turns to normal.

I want to keep my grid but still can use the button.

geeksportal("all")

function geeksportal(c) {
  var x, i;

  x = document.getElementsByClassName("column");

  if (c == "all") c = "";

  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");

    if (x[i].className.indexOf(c) > -1)
      w3AddClass(x[i], "show");
  }
}

function w3AddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");

  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

function w3RemoveClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
  element.className = arr1.join(" ");
}

// Add active class to the current
// button (highlight it)
var btnContainer = document.getElementById("filtering");
var btns = btnContainer.getElementsByClassName("bttn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {

    var current =
      document.getElementsByClassName("active");

    current[0].className =
      current[0].className.replace(" active", "");

    this.className += " active";
  });
}
/* Wildcard styling */

* {
  box-sizing: border-box;
}


/* Padding for whole body */

body {
  padding: 15px;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  background-color: #e4c0f5;
}


/* Styling h2 tag */

h1 {
  Color: rgb(240, 6, 135);
  word-break: break-all;
  font-style: oblique;
}


/* Anchor tag decoration */

a {
  text-decoration: none;
  color: #5673C8;
}

a:hover {
  color: lightblue;
}

.container {
  max-width: 1200px;
  margin: auto;
}

.row {
  margin: 0px -10px;
  padding: 8px;
  display: grid;
  gap: 5px;
  grid-template-areas: initial;
}

.Byyourside {
  grid-column: 1 / 2;
  grid-row: 2 / 4;
}

.Onlyyousheet {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}

.YourGroup {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

.YourGroup1 {
  grid-column: 2 / 3;
  grid-row: 3 / 4;
}

.row>.column {
  padding: 6px;
}

.content:hover {
  filter: drop-shadow(4px 4px 60px gray);
  transform: scale(1.01);
}

.column {
  float: left;
  width: 25%;
  display: none;
}


/* Content decoration */

.content {
  background-color: white;
  padding: 10px;
  border: 1px solid gray;
  transition: 0.5s;
  border-radius: 10px;
}


/* Paragraph decoration */

p {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.show {
  display: block;
}


/* Style the filter buttons */

.filtering {
  text-align: center;
}

.bttn {
  padding: 8px 14px;
  background-color: gray;
  border-radius: 10px;
}

.bttn:hover {
  background-color: #007EE5;
  opacity: 0.8;
}

.bttn.active {
  background-color: #007EE5;
  color: white;
  `Z`
}


/* Window size 850 width set */

@media screen and (max-width: 850px) {
  .column {
    width: 50%;
  }
}


/* Window size 400 width set */

@media screen and (max-width: 400px) {
  .column {
    width: 100%;
  }
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="css.css">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Portfolio</title>
</head>

<body>

  <!-- Title and tag -->
  <div class="container">
    <h1>Kiet Vu</h1>
    <h3>Ailly's house photography</h3>
    <hr>

    <!-- Content of the body-->
    <h2>Our services</h2>

    <!-- Button foreach group -->
    <div id="filtering">
      <button class="bttn active" onclick="geeksportal('all')">
            Show all
            </button>
      <button class="bttn" onclick="geeksportal('Byyourside')">
            By your side
            </button>
      <button class="bttn" onclick="geeksportal('Onlyyou')">
            Only you
            </button>
      <button class="bttn" onclick="geeksportal('YourGroup')">
            Your Group
            </button>
    </div>

    <!-- Portfolio Gallery Grid -->
    <div class="row">
      <div class="Byyourside">
        <div class="column Byyourside">
          <div class="content">
            <img src="IMAGE/nature/IMG20220815131449.jpg" alt="HTML" style="width:100%">
            <h3>
              <a href="#">
                <br>
                <br>
                <br>
                <br>
                <br>
                <br>
                <HR> Nature
              </a>
            </h3>

            <p>
              Don't worry about missing your moment just make your trip accomplished while we are capturing the most beautiful moments of nature, and architecture around you.
            </p>

          </div>
        </div>
      </div>
      <div class="Onlyyousheet">
        <div class="column Onlyyousheet">
          <div class="content">
            <img src="IMAGE/_KIE8837.jpg" alt="CSS" style="width:100%">
            <h3>
              <a href="#">
                <hr> Portrait
              </a>
            </h3>

            <p>
              Creating your best album so far with us. Ofcourse we also have a beautify-team following you to make sure you are always beautiful.
            </p>

          </div>
        </div>
      </div>
      <div class="YourGroup">
        <div class="column YourGroup">
          <div class="content">
            <img src="IMAGE/KIET5409.jpg" alt="" style="width:100%">
            <h3>
              <a href="#">
                <HR> Yearbook
              </a>
            </h3>

            <p>
              Give us the most special time in your student life, you won't be disappointed.
            </p>

          </div>
        </div>
      </div>
      <div class="YourGroup1">
        <div class="column YourGroup1">
          <div class="content">
            <img src="IMAGE/KIET8675.jpg" alt="" style="width:100%">
            <h3>
              <a href="#">
                <HR> Story teller
              </a>
            </h3>

            <p>
              With this choice, we will give you a table of content to choose which included the ideas, costume, locations, ...
            </p>

          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="java.js">
  </script>
</body>

</html>

Dark mode switcher in Nuxt 3 not working with official @nuxtjs/color-mode

I wanted to implement dark mode on my Nuxt app using tailwind and the recommended @nuxtjs/color-mdoe module. Testing tailwind’s dark: classes went fine and worked as expected, however I can’t make a button switcher work to set the color mode programmatically.

I installed in devDeps the module in version 3.2.0, which should be compatible with Nuxt 3, according to the docs

"@nuxtjs/color-mode": "^3.2.0"

And applied the proper configuration in nuxt.config.ts

modules: [ '@nuxtjs/color-mode' ],
colorMode: {
    classSuffix: '',
    preference: 'system',
    fallback: 'dark'
  }

Since I wanted to place the switch in the header here’s what I did in the component:

<template>
  <header class="contain py-[15px] flex items-center justify-between backdrop-blur-3xl">
    <button @click="toggleDarkMode($colorMode.preference === 'dark' ? 'light' : 'dark')">
      <nuxt-icon v-if="$colorMode.preference === 'dark'" name="sun"/>
      <nuxt-icon v-else name="moon"/>
    </button>
  </header>
</template>
<script setup>
function toggleDarkMode(theme) {
  useColorMode().preference = theme
}
</script>

The classes are actually toggling when I manually change the color mode from my os (win11) settings, but clicking the button won’t replicate the same behavior. The mode seems to be switching since the icon does change accordingly.

Looking at the docs and tutorials I found elsewhere it should just work like that. Do I needd to set the mode as global state inside the store? Should I call the hook in a root level component?

How to make the datatable react to filters?

I have applied a filter on a column of the datatable and everything(selecting filters, clear filters) works just fine, but when i click apply, the data in the table does not change based on the filter

I have honestly tried everything but nothing works

Why isn’t this Hello World Splide.js code working?

Maybe I am just too tired, but the most basic Splide example isn’t working and I’ve spent hours on it. Does nayone have any insight? No errors. Nothing seems wrong, it just won’t move off the first image. It will drag a bit to show the second picture, but it won’t navigate to it. Buttons don’t work either.

  document.addEventListener( 'DOMContentLoaded', function() {
                var splide = new Splide( '.splide').mount();
            } );
<html>
    <head>         
        <meta charset="UTF-8">
        <title>Splide test</title>
        <script src="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/js/splide.min.js"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/css/splide.min.css">        
    </head>
    <body>
        <section id="splide" class="splide" aria-label="Splide Basic HTML Example">
            <div class="splide__track">
                <ul class="splide__list">
                    <li class="splide_slide">         
                        <img alt="one" src="https://zaydite.com/images/uploads/42/181/one.jpg">                    
                    </li>
                    <li class="splide_slide">
                        <img alt="two" src="https://zaydite.com/images/uploads/42/181/two.jpg">                  
                    </li>
                    <li class="splide_slide">
                        <img alt="three" src="https://zaydite.com/images/uploads/42/181/three.jpg">                        
                    </li>
                    <li class="splide_slide">      
                        <img alt="four" src="https://zaydite.com/images/uploads/42/181/four.jpg">
                    </li>
                    <li class="splide_slide">                
                        <img alt="five" src="https://zaydite.com/images/uploads/42/181/five.jpg">
                    </li>
                </ul>
            </div>
        </section>
        <script>
          
        </script>
    </body>

Blank screen after building app in React Native

After installing and customizing my basic react navigation setup, After building the app a blank screen appears with no errors in the console.

I added {{flex:1}} to the SafeAreaView
I tried uninstalling, deleting node modules, gradle clean and nothing is working.

Navigation.js file

import *as React from "react";
import IndexScreen from "./Screens/Index";
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { NavigationContainer } from '@react-navigation/native';
import { SafeAreaView } from "react-native-safe-area-context";
const Stack = createNativeStackNavigator();

const Navigation = () => {
    <SafeAreaView style={{flex:1}}>
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Index">
                <Stack.Screen name="Index" component={IndexScreen} />
            </Stack.Navigator>
        </NavigationContainer>
    </SafeAreaView>
    
}
export default Navigation;

App.js file

import React from 'react';
import Navigation from './src/Navigation';

const App = () =>{
  return (
      <Navigation />
  )}

export default App;

state updates with the old and the new values at the same time

been trying to update initUsers values on the DOM so the initial state values it works just fine but when i update initUsers it renders different values from the expected ones .

so basically entriesNum get a number as an event and based on it changes the order of initUsers state value from something like this :

enter image j here

to this :

enter image description here

`  const [itteratedUsers, setItteratedUsers] = useState([...users]);
  const [Newobj, setNewobj] = useState([]);
  const [isNewObj, setIsNewObj] = useState(false);
  const [initUsers, setUsers] = useState(users);`

`  const entriesNum = (event) => {
    
 
    const newi = Math.ceil(5 / event.target.value);

     for (let i = 0; i < newi; i++) {
      if (itteratedUsers.length >= event.target.value) {
        Newobj.push(
          itteratedUsers.splice(0, event.target.value).reduce((obj, key, i) => {
            obj[i] = key;
            return obj;
          }, {})
        );
      } else {
        Newobj.push(
          itteratedUsers.splice(0).reduce((obj, key, i) => {
            obj[i] = key;
            return obj;
          }, {})
        );
      }
    }
     
setNewobj([]);
    setIsNewObj(true);
    setUsers(Newobj);
    
    setItteratedUsers(users);

    
  };`

because i have two forms of initUsers i hade to set two ways of destructuring like this :

`*{isNewObj
                ?  initUsers.map((objUser ) => (
                    < >
                      {Object.keys(objUser).map((numo) => (
                        <div
                          key={numo}
                          className="contacts-info  border-solid border-2 border-black table-row w-full "
                        >
                          <input type={"checkbox"} className={`${shortcut}`} />
                          <div className={`${shortcut}`}>
                            {objUser[numo].index}
                          </div>
                          <div className={`${shortcut}`}>
                            {objUser[numo].email}
                          </div>
                          <div className={`${shortcut}`}>
                            {objUser[numo].access}
                          </div>
                        </div>
                      ))}
                    </ >
                  )) :
                
                initUsers.map(({ index, handle, phone, email, access }) => (
                    <div
                      key={id}
                      className="contacts-info  border-solid border-2 border-black table-row w-full "
                    >
                      <input type={"checkbox"} className={`${shortcut}`} />
                      <div className={`${shortcut}`}>{index}</div>
                      <div className={`${shortcut}`}>{handle}</div>
                      <div className={`${shortcut}`}>{phone}</div>
                      <div className={`${shortcut}`}>{email}</div>
                      <div className={`${shortcut}`}>{access}</div>
                    </div>
                  ))}*`

the second condition destructur the initUsers when it is not nested and shows the following result :

enter image description here

and the first one destructure it in its nested form and shows the following result :

enter image description here

so instead of getting 5 rows the result of destructuring the nested initUsers i get 9 .

Apply template string dynamically in JavaScript [duplicate]

I would like to apply a string as a template but dynamically.

I have a string, coming from a config file, with the same “format” as a template string. For instance 'Hello, ${name}!' And I’d like to evaluate it as a template string, but dynamically, controlling the values in scope. Something like:

const input  = 'Hello, ${name}!';
const result = applyTemplate(input, {name: 'world'});
// result is 'Hello, world!'

Surprisingly, I have not found any way to achieve this. Any idea?

why double click is needed to play iframe video using JS

I have an iframe youtube video which I am trying to click using a Tag. I got everything to work however I need to click on the image twice in order for the video to play. How can I make it a single click? Is it a focus issue to iframe?

<center><a href="javascript:void(0)" class="addto" id="playvideo" target="_self" onclick="someFunction2()">
    <img src="www.pngegg.com/pngimages/299/1011/png-clipart-moringa-leaf.png" width="300">
      
</a></center>




<script>
 function someFunction2(){

 $("#playvideo").click(function(){
 $("#widget2")[0].src = "https://www.youtube.com/embed/JtdGWMH28ns?autoplay=1";
    });
 }

I wish to click on the image with a single click to play the video rather click on it twice to play the video. any help

Labels disappear from Google chart when animation occurs

When my chart animates to display new data, the labels on the columns disappear and are not rendered again. All the the data is being imported correctly and displayed on the columns. The label data is only displayed on the initial render of the chart.

The success handler returns ‘values’, an array of three numbers, for example: [10, 8, 2] and is working correctly.

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <script src="https://www.gstatic.com/charts/loader.js"></script>
</head>

<body>
  <div id="genderChart" style="overflow: hidden"></div>

<script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(initChart);
    
    var chart;
    var options = {
      legend: {position: "none"},
      chartArea: {width:'100%'},
      animation: {duration: 1000, easing: 'out'}
    };

    function initChart() {
      chart = new google.visualization.ColumnChart(document.getElementById('genderChart'));
      drawGenderChart();
    }

    function drawGenderChart() {
      google.script.run.withSuccessHandler(function (values){
        genderData = values;
      }).getGenderData();

      label00 = JSON.stringify(genderData[0]);
      label01 = JSON.stringify(genderData[1]);
      label02 = JSON.stringify(genderData[2]);

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Gender');
      data.addColumn('number', 'Students');
      data.addColumn({role: 'style'});
      data.addColumn({role: 'annotation'});

      data.addRows([
        ['Male', genderData[0], '#9fc5e8', label00],
        ['Female', genderData[1], '#d5a6bd', label01],
        ['Non-binary', genderData[2], '#b7b7b7', label02]
      ]);

      chart.draw(data, options);
    }

    setInterval(drawGenderChart, 1000);

  </script>
</body>

</html>