Why are my buttons not invoking functions in html?

beginner here, I’m trying to make a display with buttons that could display additional information. I went about attempting this by having the information be set to display: none; and then setting them to display: inline; by invoking functions with a button.

However, it seems my buttons are not able to invoke the needed functions since even after attempting to console log the functions, they don’t respond.

Here’s the code all braces ie. {{}} are anki tags:

<style>
.card {
  font-family: Comic Sans MS; //Kid font
  font-size: 20px;
  text-align: center;
  color: black;
  background-color: white;
}

li {
    text-align:left;
    display:none;

}

button{
    display:block;
    width:28%;
    padding:auto;
    margin:auto;
}

.mono{ 
    font-family:"Courier New";
    font-size: 1.18em; 

    font-weight:bold;


    width:50%;
    margin: auto;
}


.etymology {
    margin:auto;
    margin: 0 0 1em 0;
    display:none;

}

.info{

    margin: 0 0 1em 0;
    display:none;


}
</style>

{{FrontSide}} // all tags with braces are anki tags

<hr id=answer>

<h2>{{def}}</h2>

<button onlclick="synonyms()"> Common Syn.</button>

<ul>
    <li>{{c1}}, </li><li>{{c2}}, </li><li>{{c3}}, </li><li>{{c4}}, </li><li>{{c5}}</li>
</ul>


<div class="mono"> 

    <div class="smol_details">

        <div class="etymology">{{etymology}}<br> "{{source_language}}"</div> 
        <button onlclick="etymology()">Language info </button>

        <div class="info">{{usage_cat}} {{recognition}} {{book}} <br>{{commentary}}</div>
        <button onlclick="data()"> data data</button>

    </div>

</div>


<script>
    function synonyms() {
    document.querySelectorAll("li").style.display = "inline";
    
    console.log("cliced");
} 

    function etymology() {
    document.querySelectorAll(".etymology").style.display = "inline";
console.log("cliced");
} 

    function data() {
    document.querySelectorAll(".info").style.display = "inline";
console.log("cliced");
} 

</script>

I need to have the

  • , .etymology, and .data be visible when the buttons related to them are clicked. Any help is appreciated
  • Javascript school grades calculator

    I need help with my calculator:
    It should calculate average grades,all grades,all wroten grade:5 and all wroten 1

    Document let tab = [], i = 0, max, min; do { tab[i] = parseInt(prompt(“Podaj jakąś wartość. n Zero kończy wprowadzanie danych:”)); i++; } while (tab[i – 1]); max = tab[0]; min = tab[0]; for (i = 1; i max) max = tab[i]; if (tab[i] Największa wartość to ${max} a najmniejsza to ${min}.`);

    Loop,tab index
    It need to wrote it in page (not on console)

    Flask can’t get session var from javascript

    I have a site with a dual form, first form is to select an analysis and then the rest of the form is shown.

    The chosen analysis is saved as a flask session['sel_analysis']

    This all works as expected.

    The problem:
    1: Open two tabs on the same site and select different analyses on the sites
    2: The first tab still has the first analysis selected in the form and i can change values but when i submit the form the session from the second site with another analysis is loaded so the form is saved on the wrong analysis.

    How did i try to solve it
    When a site is inFocus check if the session['sel_analysis] is the same as the selected_analysis in the form and do a location.reload() if it’s not the same.

    The problem with the solution:
    When i in javascript do a fetch on the api call (Code for the backend api call below) the session['sel_analysis'] is always None, so how can i get the session in an api call from javascript?

    Python code:

    app = Flask(__name__)
    app.config['SECRET_KEY'] = "Very secret"
    CORS(app, supports_credentials=True)
    
    @app.route('/edit', methods=['GET', 'POST'])
    def edit():
        global systems_obj_list
        sel_analysis = None
        try:
            if session["sel_analysis"]:
                for s in systems_obj_list:
                    if s == session["sel_analysis"]:
                        sel_analysis = s
        except Exception as e:
            session["sel_analysis"] = None
        ...
        return render_template('edit.html', systems=systems_obj_list, selected_system=sel_system)
    
    @app.route('/api/get-session-analysis', methods=['GET'])
    def get_session_analysis():
        """Return the selected analysis from session
    
        Returns:
            json: Key analysis gives The name of the analysis or None if there is no session available
        """
        if request.method == 'GET':
            sys = session.get("sel_analysis")
            print(sys)
            if sys == None: sys = ""
            response = jsonify({"analysis": sys})
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
    

    The javascript that calls the function:

    async function getSessionAnalysis() {
        var analysis = await fetch('http://localhost/api/get-session-analysis', {
                method: 'GET',
                credentials: 'same-origin'
        }).then((response) => {
                j = response.json();
                console.log(j);
                return j;
            }).then((myJson) => {
                var s = myJson['analysis'];
                console.log(s);
                return s;
            });
        console.log(analysis);
        return analysis
    }
    

    The HTML for the code that runs the fetch:

    {% if selected_system != None %}
        <script>
            // Check if the site is focused again and if it is check if another analysis is chosen in the same session and reload the site if it is
            console.log($('#p_sel_sys').text().replace("Currently selected analysis:  ", ""));
            var sessionAnalysis = getSessionAnalysis();
            console.log(sessionAnalysis);
            window.onfocus = function () {
                if ("{{ selected_system.get_name() }} " != sessionAnalysis) {
                    console.log("reload");
                    // location.reload();
                }
            }
        </script>
    

    The variable selected_system.get_name() is a variable passed from backend on return on the site to get the chosen analysis in the first form, i want to check if this is the same as the session since then i can never have 2 tabs open with different analyses chosen to accidently overwriting one with another.

    Like i said in python i print the session['sel_analysis'] it’s always None and i don’t know why?

    Uncaught TypeError: props.setSearchValue is not a function

    I’m very new to react and javascript. I’m trying to build a IMDb webpage and I’m stuck with this problem.

    I’m trying to get my search to work but I get this problem: “Uncaught TypeError: props.setSearchValue is not a function” and refers me to this line of code:

    <input className='form-control' placeholder='Search CARLDb...' value={props.value} onChange={(event) => props.setSearchValue(event.target.value)}></input>
    

    I’m not really sure which code to correct here. The code above is located in my file called SearchBox.js and I’m reaching it in my navbar like this:

    import React from "react";
    import { Link } from "react-router-dom";
    import logo from "../carldb2.png";
    import "bootstrap/dist/css/bootstrap.min.css";
    import "./components.css";
    import SearchBox from "./SearchBox";
    import SearchList from "./SearchList";
    
    
    const Navbar = (props) => {
      return (
        <div>
        <nav className="navbar">
        <div className="nav-center d-flex">
          <Link to="/">
            <img className="logo" src={logo} alt="logo" />
          </Link>
          <SearchBox
            searchValue={props.searchValue}
            setSearchValue={props.setSearchValue}
          />
        </div>
      </nav>
      <div className="container-fluid search-list">
      <SearchList
          tvShow={props.movieSearch}
          handleFavouritesClick={props.addRecentlyViewed}
        />
          <Link to="/search">
            <button className="results">See all results for "{props.searchValue}"</button>
          </Link>
      </div>
      </div>
      )
    }
    
    export default Navbar
    

    searchValue, setSearchValue, movieSearch and recentlyViewed all comes from my homepage:

    import React, { useEffect, useState } from "react";
    
    import MovieList from "./MovieList";
    import "bootstrap/dist/css/bootstrap.min.css";
    import "./components.css";
    import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
    import { faEye, faFire } from "@fortawesome/free-solid-svg-icons";
    import RecentlyViewed from "./RecentlyViewed";
    
    import Trailer from "./Trailer";
    
    const Homepage = () => {
      const [tvShow, setTVShow] = useState([]);
      const [movieSearch, setMovieSearch] = useState([]);
      const [searchValue, setSearchValue] = useState("");
      const [recentlyViewed, setRecentlyViewed] = useState([]);
    
      const getMovieRequest = async () => {
        const url = `https://api.themoviedb.org/3/movie/top_rated?api_key=1e08baad3bc3eca3efdd54a0c80111b9&language=en-US&page=1`;
    
        const response = await fetch(url);
        const responseJson = await response.json();
    
        setTVShow(responseJson.results);
      };
    
      const getSearchRequest = async () => {
        const search_url = `https://api.themoviedb.org/3/search/movie?api_key=1e08baad3bc3eca3efdd54a0c80111b9&language=en-US&query=${searchValue}&page=1&include_adult=false`;
    
        const response = await fetch(search_url);
        const responseJson = await response.json();
    
        if (responseJson.results) {
          setMovieSearch(responseJson.results.slice(0,5));
        }
      };
    
      useEffect(() => {
        if (searchValue) {
          getSearchRequest();
        }
      }, [searchValue]);
    
      useEffect(() => {
        getMovieRequest();
      }, []);
    
      useEffect(() => {
        const recentlyMovies = [
          ...new Set(
            JSON.parse(localStorage.getItem("react-movie-app-favourites"))
          ),
        ];
    
        if (recentlyMovies) {
          setRecentlyViewed([...new Set(recentlyMovies.slice(0, 5))]);
        }
      }, []);
    
      const saveToLocalStorage = (items) => {
        localStorage.setItem("react-movie-app-favourites", JSON.stringify(items));
      };
    
      const addRecentlyViewed = (movie) => {
    
        recentlyViewed.forEach((item) => {
          let index = recentlyViewed.indexOf(item);
          if (item.id === movie.id) {
            recentlyViewed.splice(index, 1);
          }
        });
        const newRecentlyViewed = [movie, ...recentlyViewed];
        setRecentlyViewed([...new Set(newRecentlyViewed)].slice(0, 5));
        saveToLocalStorage(newRecentlyViewed);
      };
    
      return (
        <div>
          <Trailer />
          <h1 className="popular-title">
            <FontAwesomeIcon id="fire" icon={faFire} />
            Top Rated Movies
          </h1>
          <div className="container-fluid movie-app">
            <div className="row">
              <MovieList
                tvShow={tvShow}
                handleFavouritesClick={addRecentlyViewed}
              />
            </div>
          </div>
          <h1 className="popular-title">
            <FontAwesomeIcon id="fire" icon={faEye} />
            Recently Viewed
          </h1>
          <div className="container-fluid movie-app">
            <RecentlyViewed tvShow={recentlyViewed} />
          </div>
        </div>
      );
    };
    export default Homepage;
    

    APP.js

    import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
    import Homepage from './components/Homepage';
    import Footer from './components/Footer';
    import Search from './components/Search';
    import Navbar from './components/Navbar';
    
    function App() {
      return (
        <Router>
          <Navbar/>
          <Routes>
            <Route path="/" element={<Homepage />} />
            <Route path="/search" element={<Search />} />
          </Routes>
          <Footer />
        </Router>
      );
    }
    
    export default App;
    

    I know theres alot of code linked right now, let me know if I can edit it somehow so it’s easier to see the problem.

    How to do a IF statement with hours and minutes from Date() in JavaScript?

    I do this post because I’ve a problem…

    I do a website for a shop and I want see “Open” when the store is open and “Close” when the store is close. Normally. BUT! Because they have a BUT! The store close at 12:30AM and 6:30PM. So, when I do the condition like you can see below(The hour is in French format. 18 = 6PM), my console.log print “Open” IF (hour <= 12) AND IF (minute <= 30). So when it’s 10:30AM, console.log = Open, when it’s 10:31AM, console.log = Close. Like if it’s 11:30AM, console.log = Open, when it’s 11:31AM, console.log = Close.

    function etatMagasin() {
        let today = new Date()
        let day = today.getDay()
        let hour = today.getHours()
        let minute = today.getMinutes()
        let second = today.getSeconds()
        // Lundi à Vendredi
        if (day < 6) {
            if (hour >= 9 && (hour <= 12 && minute <= 30)) {
                console.log("Open")
            } else if (hour >= 14 && (hour <= 18 && minute <= 30)) {
                console.log("Open")
            } else {console.log("Close")}
        } else if (day == 6) {
            if (hour >= 10 && hour <= 16) {
                console.log("Open")
            } else {console.log("Close")}
        } else {console.log("Close")}
    
        console.log(day + ":" + hour + ":" + minute + ":" + second)
    
        t = setTimeout(function() {etatMagasin()}, 1000)
    } etatMagasin()
    

    So nobody have an idea how to solve that? I really don’t find how to do that… :/

    Thank you!

    detecting device orientation without device orientation event [duplicate]

    Is there a JS libary with which I can detect device orientation over all browsers with the same value range? I need a way for a Three.js website to detect the device orientation of mobile devices so I can rotate my camera the same way. The web api device orientation event is not optimal because every browser handels the values diffrent.
    Thanks in advance for your suggestions.

    Show Hide vanilla JavaScript [duplicate]

    i have to use vanilla javascript. I have one function, which is a show/hide block in htmml,
    but i receive a Cannot read properties of null (reading ‘addEventListener’).

    Below is the code

    const btnContent = document.querySelector('.show-hide_btn');
    const btnText = document.querySelector('.show-hide_text');
    const btnContent2 = document.querySelector('.show-hide_btn-2');
    const btnText2 = document.querySelector('.show-hide_text-2');
    
    function onceTwo (btn, content) {
            btn.addEventListener('click', function () {
                content.classList.toggle('display-none');
            });
    }
    
    onceTwo(btnContent, btnText);
    onceTwo(btnContent2, btnText2);
    

    swiperjs sets wrong height for the first picture

    Since I added autoheight for my swiperjs the div height for the first picture is false,
    when I swipe and swipe back the picture gets the correct height. What can I add css or js wise to prevent this?

    my js:

        var W = {
            init: !0,
            direction: "horizontal",
            touchEventsTarget: "wrapper",
            initialSlide: 0,
            speed: 300,
            cssMode: !1,
            updateOnWindowResize: !0,
            resizeObserver: !0,
            nested: !1,
            createElements: !1,
            enabled: !0,
            focusableElements: "input, select, option, textarea, button, video, label",
            width: null,
            height: null,
            preventInteractionOnTransition: !1,
            userAgent: null,
            url: null,
            edgeSwipeDetection: !1,
            edgeSwipeThreshold: 20,
            autoHeight: !1,
            setWrapperSize: !1,
            virtualTranslate: !1,
            effect: "slide",
            breakpoints: void 0,
            breakpointsBase: "window",
            spaceBetween: 0,
            slidesPerView: 1,
            autoHeight: 1,
            slidesPerGroup: 1,
            slidesPerGroupSkip: 0,
            slidesPerGroupAuto: !1,
            centeredSlides: !1,
            centeredSlidesBounds: !1,
            slidesOffsetBefore: 0,
            slidesOffsetAfter: 0,
            normalizeSlideIndex: !0,
            centerInsufficientSlides: !1,
            watchOverflow: !0,
            roundLengths: !1,
            touchRatio: 1,
            touchAngle: 45,
            simulateTouch: !0,
            shortSwipes: !0,
            longSwipes: !0,
            longSwipesRatio: 0.5,
            longSwipesMs: 300,
            followFinger: !0,
            allowTouchMove: !0,
            threshold: 0,
            touchMoveStopPropagation: !1,
            touchStartPreventDefault: !0,
            touchStartForcePreventDefault: !1,
            touchReleaseOnEdges: !1,
            uniqueNavElements: !0,
            resistance: !0,
            resistanceRatio: 0.85,
            watchSlidesProgress: !1,
            grabCursor: !1,
            preventClicks: !0,
            preventClicksPropagation: !0,
            slideToClickedSlide: !1,
            preloadImages: !0,
            updateOnImagesReady: !0,
            loop: !1,
            loopAdditionalSlides: 0,
            loopedSlides: null,
            loopFillGroupWithBlank: !1,
            loopPreventsSlide: !0,
            rewind: !1,
            allowSlidePrev: !0,
            allowSlideNext: !0,
            swipeHandler: null,
            noSwiping: !0,
            noSwipingClass: "swiper-no-swiping",
            noSwipingSelector: null,
            passiveListeners: !0,
            maxBackfaceHiddenSlides: 10,
            containerModifierClass: "swiper-",
            slideClass: "swiper-slide",
            slideBlankClass: "swiper-slide-invisible-blank",
            slideActiveClass: "swiper-slide-active",
            slideDuplicateActiveClass: "swiper-slide-duplicate-active",
            slideVisibleClass: "swiper-slide-visible",
            slideDuplicateClass: "swiper-slide-duplicate",
            slideNextClass: "swiper-slide-next",
            slideDuplicateNextClass: "swiper-slide-duplicate-next",
            slidePrevClass: "swiper-slide-prev",
            slideDuplicatePrevClass: "swiper-slide-duplicate-prev",
            wrapperClass: "swiper-wrapper",
            runCallbacksOnInit: !0,
            _emitClasses: !1,
        };
    

    how it looks like

    already tried adding the following:
    preloadImages:1,
    updateOnImagesReady:1,
    observer:1,
    observeParents:1,

    Toggle method isnt working for multiple classes. Accordion

    I had to create few accordions for my sidebar. Im using SASS with BEM, JS, and Vite.js for my project. Im not so food with JS. Toggle method helped me a lot with creating “hamburger”, so i decided to use it in accordions. It actually worked but only with the first one. I searched and tried few ideas, but they doesnt work propperly too. So here is the question. Is it possible to create toggle for multiple accordions, or it is error in my code?

    HTML         
    <!--First accordeon working good-->
              <div class="canvasbar__item accordeon">
                <div class="accordeon-box">
                  <a href="" class="accordeon-box__link">Меню</a>
                  <button class="accordeon-box__btn">
                    <img src="/src/assets/icons/icons8-plus-24.png" alt="plus">
                  </button>
                </div>
                <ul class="accordeon__child">
                  <li class="accordeon__item">
                    <a href="">Холодні закуски</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Салати</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Гарячі закуски</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Паста та різотто</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Супи</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Гарніри</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">М'ясні страви</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Рибні страви</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Мангал меню</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Роли</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Дитяче меню</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Бенкетне меню</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Десерти</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Бізнес ланчі</a>
                  </li>
                </ul>
              </div>
    
              <!--Second accordeon doesnt-->
              <div class="canvasbar__item accordeon">
                <div class="accordeon-box">
                  <a href="" class="accordeon-box__link">Бар</a>
                  <button class="accordeon-box__btn">
                    <img src="/src/assets/icons/icons8-plus-24.png" alt="plus">
                  </button>
                </div>
                <ul class="accordeon__child">
                  <li class="accordeon__item">
                    <a href="">Віскі</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Коньяк</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Горілка</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Ром Джин Текіла</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Вермути Настоянки</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Вина Ігристі вина</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Пиво</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Напої Соки</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Алкогольні коктейлі</a>
                  </li>
                  <li class="accordeon__item">
                    <a href="">Кава Чай</a>
                  </li>
                </ul>
              </div>
    
    SCSS
    
    .accordeon {
    
        .accordeon-box {
            display: flex;
            justify-content: space-between;
            text-align: center;
            align-items: center;
    
            &__btn {
                border: none;
                background: none;
                align-items: center;
                display: flex;
    
                img {
                    width: 20px;
                    height: 20px;
                    transition: all 0.3s ease-in-out;
                }
            }
    
            &__btn:focus {
    
                img {
                    transform: rotate(45deg);
                }
            }
        }
    
        &__child {
            margin-left: 18px;
            background-color: white;
            height: 0;
            overflow: hidden;
            transition: height 0.2s ease-in-out;
    
            &--active {
                overflow: auto;
                height: fit-content;
            }
        }
    
    
        &__item {
    
            a {
                margin: 10px 0;
                font-size: 14px;
            }
    
            a:hover {
                color: $hover-color;
            }
        }
    }
    
    JS
    
    export function toggleMenu() {
        const accordeon = document.querySelector(".accordeon-box__btn");
        const child = document.querySelector(".accordeon__child");
    
        accordeon.addEventListener('click', () => {
            child.classList.toggle('accordeon__child--active');
        });
    }
    

    Argument of type ‘{ year: number; month: number; date: number; }’ is not assignable to parameter of type ‘DateObjectUnits’

    I am getting this error in my vscode when I hover my code:

    Argument of type '{ year: number; month: number; date: number; }' is not assignable to parameter of type 'DateObjectUnits'.
      Object literal may only specify known properties, and 'date' does not exist in type 'DateObjectUnits'.ts(2345)
    

    Here my logic was created in moment library where my dates are not ok in moment and I am receiving output which my code sample is given below,

    // Moment:
    
    const date = '';
    
    const start = moment(date[0]).set({
      year: moment(date[0]).get('year'),
      month: moment(date[0]).get('month'),
      date: moment(date[0]).get('date'),
    });
    
    console.log(`This start moment Method : `, start);
    
    

    **Here is the output:
    **

    This start moment Method : 2022-12-02T09:53:35.724Z

    But when I am trying to convert this into luxon here I am not getting expected output which I am getting in Moment, here is my code sample,

    // Luxon:
    
    const date1 = '';
    
    const start1 = luxon.DateTime.fromJSDate(date1[0]).set({
      year: luxon.DateTime.fromJSDate(date1[0]).get('year'),
      month: luxon.DateTime.fromJSDate(date1[0]).get('month'),
      date: luxon.DateTime.fromJSDate(date1[0]).get('date'),
    });
    
    console.log(`This start luxon Method : `, start1);
    
    

    **Here is the output:
    **

    This start luxon Method : null

    I am receiving null in luxon as like moment I want same output // 2022-12-02T09:53:35.724Z

    **Expected output similar should be like moment: **

    This start luxon Method : 2022-12-02T09:53:35.724Z

    Find object value with the key stored in a variable [duplicate]

    Let’s say I have an array of objects like this:

    [
    {name:"Mark",surname:"Smith",age:25,status:1},
    {name:"Joe",surname:"Hill",age:21,status:7},
    {name:"John",surname:"Grant",age:29,status:14},
    {name:"Luke",surname:"Davids",age:22,status:9}
    ]
    

    and I want to sort it by name with something like this:

    sort(function(a, b) {
            var textA = a.name.toUpperCase();
            var textB = b.name.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        })
    

    and it works perfectly fine. But what happens if I don’t know the key name directly, and I want to sort it?

    I get the key name in a prop, so, in my webApp, if a user clicks on a column in a grid, I get the column name. For example, if he clicks on a surname column, I don’t know how to put the ‘surname’ in my sorting function:

    let clickedColumnName = props.column.field;
          data=JSON.parse(sessionStorage.getItem('rnList')).RNList.sort(function(a, b) {
          var textA = a.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
          var textB = b.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });