How to open a new windows on compiled electron

I have an electron application that is compiled, i want to open a new window of the electron app ( with like a website ) with a js script that i put on the console, any idea?

tried : var tag = document.createElement("p"); var text = document.createTextNode("Tutorix is the best e-learning platform"); tag.appendChild(text);

and other things but i forgot x)

hide a div between two percentages of page of scrolling

I have a div which have a menu on Elementor .I’m going to hide between my nav and after reaching 80% of the page basicly my footer. The reason i’m doing this is to prevent it from interfering with footer.

I had found some codes and i did mine , but i just hided for the firts part basically:

y > PER AND I CANT PUT THIS PART WORKINK y < PER2

https://codepen.io/nibalAn/pen/vYpXPLZ

//PER is Percentage value
var PER = 45;
var PER2 = 60;
var yInPixel, totalHeight;

//If page if with dynamic height change totalHeight and yInPixel after Resize Event
$(document).ready(function() {
  totalHeight = $(this).height();
  
  yInPixel = totalHeight * (PER / 100) - window.innerHeight;
});

$(document).scroll(function() {
  var y = $(this).scrollTop();

  if (y > yInPixel) {
  $('.bottomMenu').fadeIn();
  if (y > PER && y < PER2 ) {
  document.getElementById("bottomMenu").style.visibility = "visible"; }
  } 
  else{
    $('.bottomMenu').fadeOut();
  }
  
});
body {
  height: 1600px;
}

.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}
<div class="bottomMenu">
<a> menu  </a> </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Any idea?

How to select all checkboxes in Jquery using kendo header template?

I’m still a newb at coding and just started javascript about a month ago. Sorry for the poopy code.. Any help would me so much appreciated. Thanks..

So I have a kendo grid that I am using with razor and mvc. I will also need to bind the check mark and row changes so that it will update my drop down list (CustomerServiceCustomerCodeList)… but I will try to figure that part out when I get there… First more importantly I need to get the select all button working properly. My checkboxes are established with the client template and header template. I need to figure out how to select all the check marks in my header template part of the grid using jquery. The client template check individual boxes code works but not my check all. I’ve tried hundreds of different approaches and cant seem to get it working. Please help.

Kendo grid :

@using System.Windows
@using AITReporting.ReportService
@using EnvDTE
@using MyAITEntity
@using MyAITEntity.Quote
@using MyAITEntity.Shipment
@using MyAITEntity.User
@model IEnumerable<MyAITEntity.Shipment.ShipmentServiceLevel>
@{

    var userCustomerCode = HttpContext.Current.Session["ServiceLevelCustomerCode"];
}

@(Html.Kendo().Grid(Model)
    .Name("ServiceLevelGrid")
    .Reorderable(reorder => reorder.Columns(true))
    .Columns(columns =>
    {
        columns.Bound(s => s.IsSelected).Template(@<text></text>)
              .HeaderTemplate("<input type='checkbox' class='chkbx k-checkbox' id='selectAllCheck' />") 
              .ClientTemplate("<input type='checkbox' id='eachCheckbox' class='chkbxq k-checkbox' />")
                            .Sortable(false)
                            .Filterable(false)
    .Width(40);

        columns.Bound(s => s.ServiceLevelCode).Title("Code").Width(73);
        columns.Bound(s => s.ServiceLevelDescription);
        columns.Command(command => { command.Edit();}).Width(77);
    })
    .Sortable()
    .Scrollable()
    //.Editable(ed => ed.Mode(GridEditMode.InCell))
    .Selectable(s => s
        .Type(GridSelectionType.Row)
        .Mode(GridSelectionMode.Multiple)
    )
    .PersistSelection(false)
    .HtmlAttributes(new { style = "min-height:280px; height:280px;", id = "ServiceLevelGrid" })
    .DataSource(dataSource =>
    {
        dataSource
            .Ajax()
            //.Events(ev =>
            //{
            //    //ev.Change("CustomServiceLevel_DataSourceChange");
            //    //ev.Edit("CustomServiceLevelEdit");
            //    ev.Save("CustomServiceLevelSave");
            //    //ev.Sync("resyncChildGrid");
            //    //ev.RequestEnd("AddressBook_requestEnd");
            //})
            .Model(model =>
            {
                model.Id(s => s.ServiceLevelCode);
                model.Field(field => field.IsSelected).Editable(true);
                model.Field(field => field.ServiceLevelCode).Editable(false);
                model.Field(field => field.ServiceLevelCustomDescription).Editable(true);
            })
            .Batch(true)
            .Update(update =>
            {
                update.Action("ServiceLevelGrid_Update", "UserAccount", new {Area = "Management", CustomerCode = userCustomerCode});
                //update.Data("ServiceLevel_GetCustomList_Data");
            })
            .Read(read =>
            {
                read.Action("ServiceLevelGrid_Read", "UserAccount", new {Area = "Management", CustomerCode = userCustomerCode});
                //read.Data("ServiceLevel_GetCustomList_Data");
            });
    })
    )

@*.Events(ev => ev.DataBound("CustomServiceLevelGrid_DataBound"))*@

Here is my Jquery.

  debugger;
    //customer code dropdown list bind to grid 
    function ServiceLevel_GetCustomList_Data(event) {
        var customServiceCustomerCodeList = $("#CustomServiceCustomerCodeList").data("kendoDropDownList"),
            customServiceCustomerCodeList_DataItem = customServiceCustomerCodeList.dataItem(),
            customServiceCustomerCodeList_ItemValue = customServiceCustomerCodeList_DataItem["OrganizationCode"];

        var customServiceDataModel = {
            customerCode: customServiceCustomerCodeList_ItemValue
        }
        return customServiceDataModel;
    };



    //Checkbox grid 
    debugger;
    console.log();
    $('#ServiceLevelGrid').on("click", ".k-checkbox", function (e) {
        grdChkBoxClick(e);
    });

    function grdChkBoxClick(e) {
        var row = $(e.target).closest('tr');
        grdChkBoxUpdate(row);
    };

    };

    //individual check box select
    function grdChkBoxUpdate(row) {
        debugger;
        console.log();
        var grid = $("#ServiceLevelGrid").data("kendoGrid"),
            dataItem = grid.items().length > 0 ? grid.dataItem(row) : undefined,
            isItemChecked = ($("#eachCheckbox", row).prop("checked") === true);
        debugger;
        console.log();
        if (isItemChecked) {
            var isSelected = dataItem.IsSelected;
            dataItem.dirty = true;
            dataItem.IsSelected = true;
            console.log("isSelected: " + isSelected);
        } else {
            dataItem.dirty = true;
            dataItem.IsSelected = false;
        }
    }


    function checkAll(row) {
        $(".chkbxq").each(function () {
            debugger;
            console.log();
            // handle the checkbox logic
            // add logic to check if is checked or not and do proper handling based on that
                     $(this).attr('checked', row);

            // update dataItem to reflect changes.... (update model and dirty flag)
            grdChkBoxUpdate;

            var row = $(e.target).closest('tr');
            grdChkBoxUpdate(row);
           

        });
        }
    function checkAll(row) {
        $(".chkbxq").each(function () {
              debugger;
                      console.log();
              function sRow() {
                 var trLength = $("#ServiceLevelGrid .k - checkbox table tr").length;

                  if (trLength > 0) {
                      $("#ServiceLevelGrid .k - checkbox table tr").each(function(i) {
                          grdChkBoxUpdate(this);
                      });
                  }
              }
              var isSelected = $(".k-checkbox", "#ServiceLevelGrid thead").attr("aria-checked");
              if (isSelected !== "true") {
                  $(".k-checkbox", "#ServiceLevelGrid thead").click();
              }

                               $(this).attr('checked', row);

              var row = $(e.target).closest('tr');
              grdChkBoxUpdate(row);

                  });
    }

Need to dynamically patch the form Values on Tab change as same component is Rendered

I am Using the Angular Reactive forms and material-ui,and using the mat-tab select element, I want to patch the value on tab Change ,but on ngOnint I am already patch the value for 1 tab but as i rendering the same component on another tab, I want to change the value of formGroup another tab
Please find the screenshot of the tabs which is to be doneenter image description here

On ngOninit I am patching initially the la(life assured) and sp(spouse) form values

 if (clientAs = 'la' && this.merActiveDataLa == '') {
        this.merActiveDataLa = merData
      } else if (clientAs = 'sp' && this.merActiveDataSp == '') {
        this.merActiveDataSp = merData
      }
      if (merData) {

        this.merFormGroup.patchValue(this.merActiveDataLa);
      }

On tabChanged method I am using this concept’

tabchanged(event, forcomponentSection = undefined) {
    // console.log(event)
    if (forcomponentSection) {
      this.selectedTabForLA = event;
      console.log("Tab Valuee ",this.selectedTabForLA);
      if (this.selectedTabForLA == 1) {
             
        if (this.merActiveDataSp) {
          this.merFormPayload.patchValue(this.merActiveDataSp)
          
          console.log("I am hereeee22222",this.merFormPayload);
        }
        this.clientAs = 'sp'
      } else {
        if (this.merActiveDataLa) {
          
          
          this.merFormPayload.patchValue(this.merActiveDataLa)
          console.log("I am hereeee33333",this.merFormPayload);
        }

        this.clientAs = 'la'
      }
    } else {
      this.selectedTab = event;
    }
  }

Please helps any comments and suggestions would be in advances.

Sharing variable(s) between files in Reaact.js

Hi I’m trying to share a variable ‘myName’ that will contain username from Login2.js which processes Login.html to App.js(main file)
Here is the code for Login2.js:

import React, { Component } from "react";


// if(document.readyState === 'loading') {
//     document.addEventListener('DOMContentLoaded', afterLoaded);
// } else {
//     //The DOMContentLoaded event has already fired. Just run the code.
//     afterLoaded();
// }
//
// function afterLoaded(){
//Your initialization code goes here. This is from where your code should start
// document.readyState === "complete")
let aa = 'hello';

function authenticate(a){//authentication function
    let c = a//is the user input
    var t1 = false
    var t2 = false
    var b = c.search("[a-z][a-z][0-9][0-9][0-9][0-9][0-9]")

    if(b == 0){
        t1 = true
    }
    if(c.length == 7){
        t2 = true
    }

    return t1&&t2//output true

}




function click(){
    var n = 3;
    window.onload = function(){
        document.getElementById("myButton").onclick = function(){
            var myName = document.getElementById("myText").value;
            if(authenticate(myName)&&n!==0){
                console.log("welcome "+myName)
                let url = "http://localhost:3000/website"
                window.open(url,"_self")
            }

            else if(n === 0){
                alert("no more log-ins")
            }

            else{
                alert("you have "+n+" chances to log-in again")
                n--
            }
        }
    }
}


class Login2 extends Component {
    state = {};
    render() {
        click();
        return (
            <div>
                <label><b>Username:</b></label>
                <input placeholder="Enter Username" id="myText"></input>
                <button type="button" id="myButton"> SIGN IN </button>
            </div>
        )
    }
}
export default Login2;

And here is the code from the App.js file:

// import React from 'react';

import React, { Component } from 'react';
import './App.css';
import Navbar from './components/Navbar.js';
import { BrowserRouter as Router, Routes, Switch, Route } from 'react-router-dom';
import Home from "./components/pages/Home"
import Faq from "./components/pages/faq"
import Advocate from "./components/pages/Advocate"
import CalendarComponent from './components/pages/Calendar.js'
import Login2 from './components/pages/Login2'
import { Linking } from 'react-native'
import { Users } from './components/Backend/Users';
import { ProcessReq } from './components/Backend/ProcessReq';
import c from "./components/pages/Login2";









const Content = () => {

    return <>

        <Navbar></Navbar>

        <Home></Home>

        <Faq></Faq>

        <Advocate></Advocate>

    </>

}


function App() {
    //should load name here and output it to user as a "welcome myName to the app" message

    return (
        //this splits up our page into the main section plus an additional calendar section

        //appropriate pathing is used to get from one part to another

        <div className={"container-fluid homepage-background"}>

            <Router>

                <Routes>

                    {/* <Route path={"/"} element={<Login />} /> */}

                    <Route path="website" element={<Content />} />
                    <Route path="calendar" element={<CalendarComponent />} />
                    <Route path="/" element={<Login2 />} />
                    <Route path="website/accountInfo" element={<Users/>} />





                </Routes>

            </Router>



        </div>

    );

}



export default App;

How do you propose I shul export variables as I have tried module.exports and require but it didn’t work among other methods. Thank you in advance!

Insert image with custom header to Google Apps Script Spreadsheet cell

I need to replicate the =IMAGE(url) functionality but calling it with a custom header param

Basically adding into the cell =FETCHIMAGE() and getting it to return the image in the cell – but the image is called from an api that needs a Referer header to access it

I’m new to GAS, but it seems the best way would be something like the following:

/**
 * Fetches an image with custom header param and inserts into the cell it's called from
 * 
 * @customfunction
 */
function FETCHIMAGE(){
  let ss = SpreadsheetApp.getActiveSpreadsheet()
  let sheet = ss.getSheetByName('Sheet1')

  let cell = sheet.getActiveCell()

  let imgUrl = '...'
  let headers = {Referer: '...'}

  let response = UrlFetchApp.fetch(imgUrl)
  let image = response.getBlob()

  // 1. 
  cell.setValue(image); // errors out due to permission from custom function

  // 2. 
  return image // doesn't work

}

Does anyone know how to either parse the image properly to get it to return, or set it in the cell from the custom function?

Thanks!

Append multiple To-do lists with javascript

I’m building a small to-do app.

Right now I can only add single tasks, and was wondering is there a way to add multiple to-do lists with their own tasks.

For example, list named Monday (with “buy groceries”), Tuesday (with wash dishes) etc.

I would also like to be able to delete single tasks, as I can now.

Thanks!

Here is my code:

    <body>
<div class="container">
  <header class="text-center text-light my-4">
    <h1 class="mb-4">To-do list</h1>
  </header>
  <form class="search text-center my-4">
    <label class="text-light"></label>
    <input
      class="form-control m-auto"
      type="text"
      name="search"
      autocomplete="off"
      placeholder="search tasks..."
    />
  </form>
  <ul class="list-group todos mx-auto text-light">
    <li
      class="list-group-item d-flex justify-content-between align-items-center"
    >
      <span>airline ticket reservation</span>
      <i class="far fa-trash-alt delete"></i>
    </li>
  </ul>

  <form class="add text-center my-4">
    <label class="text-light">Add new to-do item</label>
    <input
      class="form-control m-auto"
      type="text"
      name="add"
      autocomplete="off"
      placeholder="type here..."
    />
  </form>
</div>

<script src="app.js"></script>

…and my js code:

    const addForm = document.querySelector('.add');
    const list = document.querySelector('.todos');
    const search = document.querySelector('.search input');

    const generateTemplate = todo => {
        let html = `
        <li class="list-group-item d-flex justify-content-between align-items- 
     center">
            <span>${todo}</span>
            <i class="far fa-trash-alt delete"></i>
        </li>
        `
        list.innerHTML += html;
    }

    addForm.addEventListener('submit', e => {
        e.preventDefault();

        const todo = addForm.add.value.trim();
        if(todo.length){
            generateTemplate(todo);
            addForm.reset();
        }
    });

    //delete item

     list.addEventListener('click', e => {
        if(e.target.classList.contains('delete')){
            e.target.parentElement.remove();
        }
    });

    //search
    const filterTodos = term => {
         Array.from(list.children)
        .filter((todo) => !todo.textContent.includes(term))
        .forEach((todo) => todo.classList.add('filtered'))

        Array.from(list.children)
        .filter((todo) => todo.textContent.includes(term))
        .forEach((todo) => todo.classList.remove('filtered'))
     }

    //keyup
    search.addEventListener('keyup', () => {
         const term = search.value.trim();
        filterTodos(term);
    });
    

React.js – Can’t figure out why I’m getting this error: Invalid hook call. Hooks can only be called inside of the body of a function component

I’ll start by saying I’ve gone through this page: https://reactjs.org/warnings/invalid-hook-call-warning.html and I don’t see any reason why I will be getting this error, my versions are all fine and I don’t have duplicate Reacts.

The error is thrown when I click on a card.

This is my App.js:

const App = () => {
  const [inputString, setInputString] = useState("") //Error points to here

  const updateInput = (e) => {
    const lowerString = e.target.value.toLowerCase();
    setInputString(lowerString);
  }

  return (
    <>
    <div className='search-bar-container'>
      <img src='https://cdn-icons.flaticon.com/png/512/868/premium/868596.png?token=exp=1647880908~hmac=5e802c3c8b8423596716ca9353212d17' className='poke-ball-img' />
      <input type='text' placeholder='Search For a Pokemon!' onChange={updateInput}></input>
    </div>
    <div className='card-container'>
      <RenderPokemon input={inputString} />
    </div>
    </>
  );
}

export default App;

And this is RenderPokemon:

const RenderPokemon = (text) => {
  const [rawPokemonList, setRawPokemonList] = useState([]);
  const getPokemonData = async (id) => {
    //Move this out somehow, to avoid calling on every render 
    try {
      const res = await fetch("https://pokeapi.co/api/v2/pokemon/" + id);
      const pokemon = await res.json();
      return pokemon;
    } catch (e) {
      console.log(e);
    }
  };

  const sortPokemonList = rawPokemonList.filter((poke) => {
    if(text.input === "") {
      return poke;
    } else {
      return poke.name.toLowerCase().includes(text.input)
    }
  })

  useEffect((i) => {
    const promises = [];
    for (let i = 1; i < 152; i++) {
      promises.push(getPokemonData(i));
    }
    Promise.all(promises).then((results)=>{
      setRawPokemonList(results);
    })
  }, []);

  return (
      (sortPokemonList).map(poke=>(
        <div className='card' onClick={updatePokemonId} id={poke.id}>
          <img src={'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/' + poke.id + '.svg'} className='PokeImg' key={poke.id} id={poke.id}/>
          <div className='container'>
            <p>{poke.name}</p>
          </div>
        </div>
      ))
  )
}

export default RenderPokemon;

Custom youtube api progressbar

I looked at this question from 2014 which shows a demo of a custom youtube progressbar. I made the progressbar work on my page aswell. However in my case once a video finshed playing another one is queued. Then my progressbar goes crazy sometimes cause I think it still remembers the last song sometimes (im a bit unsure why). See my gifenter image description here

function progress(percent, $element) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({ width: progressBarWidth });
}
let mytimer = 0;
function onPlayerStateChange(event) {
     if (event.data == YT.PlayerState.PLAYING) {
     playing = true;
     var playerTotalTime = player.getDuration();
     mytimer = setInterval(function() {
        var playerCurrentTime = player.getCurrentTime();
        var playerTimeDifference = (playerCurrentTime / playerTotalTime) * 100;
        progress(playerTimeDifference, $('#progressBar'));
      }, 1000);   
}
else if(event.data == YT.PlayerState.PAUSED){
        playing = false;
}
else {
  clearTimeout(mytimer);
}

A bit further down in the code:

if (event.data == YT.PlayerState.ENDED){
    player.current_video++;
    clearTimeout(mytimer);
    playVideo();
}

So here I added clearTimeout(mytimer) to clear the timer, but I guess it doesn’t work, anyone who knows why?

Iterate through nested array of object in an Array of objects

Trying to make a select filter with all the unique coins, but not getting to the end of it correctly.

When looping through data I can get a list of all the coins like this.

const uniqueCoins = data.map((item) => {
  item.currencies.map((subItem) => 
  console.log(subItem))
});

I also want to use the Set method and spread operator to get just unique values but I’m not sure how to combine all these.

const data = [
  {
    id: "1",
    name: "Digitec",
    description: "Wir akzeptieren folgende Kryptowährungen",
    currencies: [
      {coin: "Bitcoin"},
      {coin: "Ethereum"},
      {coin: "XRP"},
    ],
    link: "webseite besuchen",
  },
  {
    id: "2",
    name: "Galaxus",
    description: "Wir akzeptieren folgende Kryptowährungen",
    currencies: [
      {coin: "Bitcoin"},
      {coin: "Monero"},
      {coin: "XRP"},
    ],
    link: "webseite besuchen",
  },
  {
    id: "3",
    name: "Brack.ch",
    description: "Wir akzeptieren folgende Kryptowährungen",
    currencies: [
      {coin: "Litecoin"},
      {coin: "Dogecoin"},
      {coin: "XRP"},
    ],
    link: "Onlineshop besuchen",
  },
];

jQuery – DataTables – How to get clicked row data – .Net 6 MVC

I’ve followed various examples but not found a solution yet. I have a MVC Web App, the data tables is loaded within a partial view (which then calls instantiateDataTable). I am adding my JS code to get the clicked row data in the view that called this partial view.

I have tried something like this, but both console.logs are coming back as undefined.

   $('#resultsGrid tbody').on('click', function() {
      var row = $(this).parents('tr')[0];
      //for row data
      //console.log(table.row(row).data().id);
      var data = $('resultsGrid').DataTable().row(this).data();
      console.log(row);
      console.log(data);
   });

See JS Fiddle

https://jsfiddle.net/p2one80j/1/

Any advise on why my code isn’t working? TIA