How to update values inside an object using DOM/HTML related functions, such as onclick or addEventListener (Vanilla Javascript)

There is something about calling a function using DOM elements, such as button (onclick, addEventListener), and calling function by updating the Browser.

I am trying to change values of a key inside an object. When I do that using click on a button in HTML, the change does not sit permanently in the object – it is only relevant to that function (onclick, such as onlick or addEventListener).

But I want to be able to change the value on click of a button in HTML, so that I can use it in other functions.

How can I solve this issue?

javascript variable in mysql datenbank speichern

ich habe ein Spiel mit Javascript erstellt dort habe ich eine variable namens usersGeld. Darin ist eine Zahl gespeichert (das Geld). Desweiteren habe ich mit php und mysql ein login system gemacht jetzt möchte ich das die Variable usersGeld für jeden angemeldeten user gespeichert wird und diese verwendet wird wen er sich einlogt. Wie ist das möglich?

Weitere infos:

Der user wird in einer Tabelle gespeichert mit usersID, Name, Pwd, und usersGeld sollte noch gespeichert werden.

Danke im voraus

Jonathan

Recursive searching returns undefined

I was just practicing some native Javascript and came across this problem. I’m building a comments widget and trying to implement a ‘reply’ button. For this I have to iterate through some n number of nested comments to find the correct one and push the reply to it’s ‘responses’ attribute. This is my code so far:

 const recursiveSearch = (object, target) => {
    if(object.id === target) return object;

    let result;
    if(object.responses.length > 0) {
     object.responses.forEach(response => {
          if(response.id === target) {
              result = response;
              console.log('match found')
              console.log(response)
              return response
          } 
          
          else if(response.responses.length > 0) recursiveSearch(response, target) 
      })   
    };

    console.log('result Is')
    console.log(result)

    return result

}

The logs show the expected behavior just fine but when looking at the end return statement is undefined. Any way to get around this?

JS/HTML/CSS Image carousel not loading correctly

I am trying to include a carousel to my website, but there’s a bug where the carousel doesn’t load properly. It flashes with the image(s) but then it disappears. You can see the video below of this error.

Chrome console shows:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')
    at showSlides (index.html:540)
    at index.html:518

You can see an example here of the problem: Video example of problem

JS is as follows:

var slidePosition = 1;
SlideShow(slidePosition);
 
// forward/Back controls
function plusSlides(n) {
  SlideShow(slidePosition += n);
}
 
//  images controls
function currentSlide(n) {
  SlideShow(slidePosition = n);
}
 
function SlideShow(n) {
  var i;
  var slides = document.getElementsByClassName("Containers");
  var circles = document.getElementsByClassName("dots");
  if (n > slides.length) {slidePosition = 1}
  if (n < 1) {slidePosition = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < circles.length; i++) {
      circles[i].className = circles[i].className.replace(" enable", "");
  }
  slides[slidePosition-1].style.display = "block";
  circles[slidePosition-1].className += " enable";
}

CSS: Link to CSS code

HTML: Link to HTML code

How to solve “Unhandled Rejection (TypeError): Failed to fetch” problem in ReactJS?

I want to fetch data from an HTTP request(Witch I created in Spring Boot), but I am getting this error:

Unhandled Rejection (TypeError): Failed to fetch

This is my code:

const getData=()=>{
    fetch('http://localhost:8080/data'
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        console.log(response)
        return response.json();
      });
  }
  useEffect(()=>{
    getData()
  },[])                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

}

solve ERR_OSSL_EVP_UNSUPPORTED in npm run serve

I get this error when I run “npm run serve”:

opensslErrorStack: [ ‘error:03000086:digital envelope routines::initialization error’ ], library: ‘digital envelope routines’,
reason: ‘unsupported’,
code: ‘ERR_OSSL_EVP_UNSUPPORTED’

I updated the npm but still have the same error.
can anyone help me?

React Link async/await does not wait code block

Hey I am trying to make small application for React-router I am trying to send API request (I do not have backend thats why im using promises) When i click Link it is redirecting not waiting my async/await could you tell me what am i doing wrong?
First thought i can pass history with props and then

history.push("/someURL");

But my second thought is if i could do this with <Link I will pass less props (history).

To sum up i need to wait until my request(promise) over after that i need to change url

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';

const StyledButton = styled.button`
  width: 100%;
  border-radius: 10px;
  background-color: #24b571;
  color: #ffffff;
  font-weight: bold;
  margin-bottom: 5px;
`;

const SaveButton = ({
  children,
  saveValidation,
  message,
  to,
  setIsLoading,
}) => {
  const promiseFunc = () =>
    new Promise((resolve) => {
      setTimeout(() => {
        resolve(5);
      }, 5000);
    });

  const onClickHandler = async (event) => {
    setIsLoading(true);
    const control = saveValidation(); // returns true or false
    if (!control) {
      toast.error(message);
      event.preventDefault();
    } else {
      try {
        const a = await promiseFunc();
        alert(a);
      } catch {
        alert('error');
      }
      console.log(control);
    }
    setIsLoading(false);
  };

  return (
    <Link to={to}>
      <StyledButton onClick={onClickHandler}>{children}</StyledButton>
    </Link>
  );
};

export default SaveButton;

SaveButton.propTypes = {
  children: PropTypes.node.isRequired,
  saveValidation: PropTypes.func.isRequired,
  to: PropTypes.string.isRequired,
  message: PropTypes.string,
  setIsLoading: PropTypes.func,
};
SaveButton.defaultProps = {
  message: 'Fill all values',
  setIsLoading: () => {},
};

Adding html mouseover function with javascript

I’m trying to write an html MUD game with javascript.
I try to print a message that shows a picture of the character performing the action when moused over.

Here is my code so far

function printMessage(message,char){

$("#messageScreen").append('<p onmouseover="showPicBottom('+char.race+','+char.pic+')" onmouseout="removePic()">'+""+message+"</p>");

}

function showPicBottom(race,pic){
    var pichtml="";
    if (origin=="Human"){
        pichtml='<img src="img/human/'+"Pic ("+pic+")"+'.PNG"/ width="200">';
    }else{
        pichtml='<img src="img/elf/'+"Pic ("+pic+")"+'.PNG"/ width="200">';
    }
    $("#picBottom").append(pichtml);
}

I always get “Uncaught SyntaxError: Unexpected token ‘,'”. I think it’s the quotation marks but I haven’t found a way. How do I fix it?

Get google translate language plain javascript on select from dropdown

I want to get the selected language from an embedded Google translate script in a dynamic php website.

I have inserted in the head

<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'el', includedLanguages: "en,el" 
 }, 'google_translate_element');
 }
 </script>
 <script type="text/javascript" src="//translate.google.com/translate_a/element.js? 
 cb=googleTranslateElementInit"></script>

and in body:

<div style="text-align:center!important;" id="google_translate_element"></div>

and translate dropdown appears ok and does the job ok.

I want to detect the selection of the language, so I run some script depending on the selection.

So far the javascript that is executing correctly is:

<script type="text/javascript">
window.setInterval(function(){
 lang = $("select.goog-te-combo option:selected").text();
alert(lang);
 },7000);
 </script>

that shows an alert window every 7 sec with the selected language text.

How do I change the above script so that is executed only on dropdown selection change?

Google Apps Script: Uncaught console error

I’m trying to debug a Console error I’m getting for one particular user.

This is the error message we are getting
enter image description here
enter image description here

The code:

    function createCopies(){
      //loading
      if(validateForm()){
        console.log("form validated")
        loadingStart();
        var copies_obj = {};
        copies_obj.number = document.getElementById("copies_number").value == "" ? 1 : document.getElementById("copies_number").value;
        console.log("copies # " + copies_obj.number)

        google.script.run.withSuccessHandler(function(res){
          document.getElementById("save-success-message").classList.remove("invisible");        
          setTimeout(function(){
            document.getElementById("save-success-message").classList.add("invisible");
          }, 4000);
          //done loading
          loadingEnd();
        }).replicateTemplate(copies_obj);
      }else{
        $('#errorNotification').toast('show');
      }
    }

Function that is being called

function replicateTemplate(copies_obj) {
  //JE Copies Reference Sheet. Put the information on the first Sheet found.
  //If we add sheets to this Spreadsheet lets add them to the right side.
  var template_list_sheets = SpreadsheetApp.openById(template_list).getSheets();
  var template_list_sheet_0 = template_list_sheets[0];

  //Start looping to create the X number of copies
  Logger.log("copies #: " + copies_obj.number)
  for(var i = 0; i < copies_obj.number; i++){
    var template_date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "MM/dd/yyyy hh:mm:ss")
    var template_list_rows = template_list_sheet_0.getLastRow();
    var fe_destination_folder = DriveApp.getFolderById(fe_folder);
    var be_destination_folder = DriveApp.getFolderById(be_folder);

    //1. Make a copy of the original template; save the original name & get the newly create template id
    var original_fe_template = DriveApp.getFileById(fe_template);
    var fe_template_name = original_fe_template.getName(); 
    var new_fe_template = original_fe_template.makeCopy().getId();

    //2. Grab the newly created template, get its url and rename the file
    var new_fe_file = DriveApp.getFileById(new_fe_template);
    var new_fe_url = new_fe_file.getUrl();
    new_fe_file.setName(fe_template_name.replace("###",template_list_rows));
    
    //3. Repeat for BE Template
    var original_be_template = DriveApp.getFileById(be_template);
    var be_template_name = original_be_template.getName();
    var new_be_template = original_be_template.makeCopy().getId();
    
    var new_be_file = DriveApp.getFileById(new_be_template)
    var new_be_url = new_be_file.getUrl();
    new_be_file.setName(be_template_name.replace("###",template_list_rows));

    //4. Update the Named Ranges
    SpreadsheetApp.openById(new_fe_template).getRangeByName("BELink").setValue(new_be_url);
    SpreadsheetApp.openById(new_be_template).getRangeByName("FELink").setValue(new_fe_url);
    SpreadsheetApp.openById(new_be_template).getRangeByName("CopyNumber").setValue(template_list_rows);

    //5. Once the files are done, move them to the destination folder
    DriveApp.getFileById(new_fe_template).moveTo(fe_destination_folder);
    DriveApp.getFileById(new_be_template).moveTo(be_destination_folder);

    //6. Add the files URL into the Reference Sheet
    var new_row = [template_list_rows, template_date, new_fe_url, new_be_url];
    template_list_sheets[0].appendRow(new_row);

  }
}

At this point I’m not really sure where to dig in order to diagnose what is wrong.
We have tested the same script with other users without any issue, but the error message doesn’t give us any clear clue.

Note: The user has access to all the files used during the script execution

click event listener method is not working on a specific div

I am trying to add an event listener to my “degree section div” but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the “degree-section” div but to no avail.

Any kind of help is welcome and appreciated

The HTML:

<body>

    <div class="loc-container">
        <div class="location">
            <h1 class="city-name">City</h1>
            <div class="weather-icon"><img src="icons/unknown.png" /></div>
       </div>
    </div>
   
    

    <div class="weather-info">

        <div class="degree-section">
            <h2 class="temp">0.0</h2>
            <span>K</span>
        </div>

        <div class="check">
            <label for="celcius">Convert</label>
            <input type="checkbox", name="celcius", id="celcius">
        </div>
    

        <div class="info-section">
            <div class="info-flex">
                <h3 class="feels-like">0K</h3>
                <h4>Feels Like</h4>
            </div>

            <div class="info-flex">
                <h3 class="humidity">0</h3>
                <h4>Humidity</h4>
            </div>

            <div class="info-flex">
                <h3 class="wind">0</h3>
                <h4>Wind</h4>
            </div>
        </div>  
    </div>
    

    <div class="top-center">
        <div class="form">
            <input type="text" name="city" id="city" required>
            <label for="city" class="label-name"><span class="search-name">Search City...</span></label>
            
        </div>
        <!-- <i class="fas fa-search search-btn"></i> -->
        <i class="material-icons search-btn" style="font-size: 35px;">search</i>
    </div>

    
    <script src="weather.js"></script>
</body>

Here is my javascript:

let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];


//let wind = document.querySelector('.wind');



async function getUrl(city){

    try{
        let theUrl = url + city + '&appid=' + apiKey;
        let response = await fetch(theUrl , {mode: 'cors'})
        let data = await response.json();
        //Get data from api and change html content based on the recieved data
        let temp_data = data.main.temp
        temp.textContent = temp_data;
        let feels_like_data = data.main.feels_like;
        feels_like.textContent = feels_like_data + "K";
        let humidity_data = data.main.humidity;
        humidity.textContent = humidity_data;
        let {icon} = data.weather[0];
        locationIcon.innerHTML = `<img src="icons/${icon}.png">`;

         //change K to C
         degree_section.addEventListener('click', ()=>{
             //logging a message just to check if it is working
            console.log("c")
        })
         
        

    }catch(err){
        let error = document.createElement('span')
        error.className = "error";
        error.textContent = "Location does not exist"
        let top_center_div = document.querySelector('.top-center')
        top_center_div.appendChild(error)
        city_name.textContent = "No city found"
    }  
}






searchbtn.addEventListener('click', (e)=>{
    let cityName = city.value;
    city_name.textContent = cityName
    console.log(cityName)
    getUrl(cityName)
})

Thank you in advance!

how do i check the textcontent inside a button. the if statement isnt recognising the text

Linkedin search result
so on the search page i want to only select the buttons with connect on them. the if statement doesnt seem to check if connect is the text content.

 var buttons = document.getElementsByClassName(
'artdeco-button artdeco-button--2 artdeco-button--secondary ember-view'


)

  for (var i = 0; i < buttons.length; i++) {
    console.log(buttons[i].textContent)
    if (buttons[i].textContent == 'Connect') {
      console.log(i)
    }
    
  }

result
Shouldnt the connect have an corresponding i?

function callback give an error while using inside onload event

I am trying to return value within onload function via callback but console give me Uncaught TypeError: callback is not a function

async function base64SquareCrop(imgbase64, size = 224, callback) {
const img = document.createElement("img");
await img.setAttribute("src", imgbase64);

let width = 1240;
let height = 698;
const min = Math.min(width, height);
const scale = size / min;
const scaledW = Math.ceil(width * scale);
const scaledH = Math.ceil(height * scale);
const dx = scaledW - size;
const dy = scaledH - size;
canvasImage.width = canvasImage.height = size;
const ctx_img = canvasImage.getContext("2d");
img.onload = function() { ctx_img.drawImage(
    img,
    ~~(dx / 2) * -1,
    ~~(dy / 2) * -1,
    scaledW,
    scaledH
);
var sss = canvasImage.toDataURL("image/png");
callback(sss);
}