How to have cursor change with buttonclick

So first I wanted to explain my problem:

I have set up a switcher on my website to toggle between normal mouse / pointer & a Lego hand as a cursor and a head as pointer. However, I can only get the cursor to show when clicking the switcher. How can I also add this pointer

(cursor: url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), pointer;)

It should be assigned to the following classes:

a, button, input, input, button, a, input, .slider, .round

I have then also added a snippet, which lets the switcher / checkbox stay on checked…
(You can see that on this video [password is 12345678]: https://easyupload.io/gknxoi)

However after a reload of the page for example, the switcher stays on checked, but the cursor doesnt show up…

I hope anybody can help me with this!!!

    < script >


      var cbs = document.querySelectorAll('input[type=checkbox]');
    for (var i = 0; i < cbs.length; i++) {
      cbs[i].addEventListener('change', function() {
        if (this.checked) {
          document.body.style.cursor =
            "url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto";
        } else {
          document.body.style.cursor = "default";
        }
      });
    }


    $(function() {
      var test = localStorage.input === 'true' ? true : false;
      $('input').prop('checked', test || false);
    });

    $('input').on('change', function() {
      localStorage.input = $(this).is(':checked');
      console.log($(this).is(':checked'));
    });

    <
    /script>
    .switcheronheader {
      position: relative;
      display: inline-block;
      width: 30px;
      height: 17px;
      margin-bottom: 2px;
    }

    .mouseswitcher {
      /*   border-left: 1px solid #248751; */
      padding-left: 20px;
    }

    .switcheronheader input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      -webkit-transition: .4s;
      transition: .4s;
    }

    .slider:before {
      position: absolute;
      content: "";
      height: 13px;
      width: 13px;
      left: 2px;
      bottom: 2px;
      background-color: white;
      -webkit-transition: .4s;
      transition: .4s;
    }

    input:checked+.slider {
      background-color: #248751;
    }

    input:focus+.slider {
      box-shadow: 0 0 1px #2196F3;
    }

    input:checked+.slider:before {
      -webkit-transform: translateX(13px);
      -ms-transform: translateX(13px);
      transform: translateX(13px);
    }

    .slider.round {
      border-radius: 34px;
    }

    .slider.round:before {
      border-radius: 50%;
    }
    <div class="mouseswitcher">

      <label class="switcheronheader">
                 <input type="checkbox" id="overheaderswitch">
                 <span class="slider round"></span>
            </label>

    </div>

Do languages like JS with a copying GC ever store anything on the cpu registers?

I am learning about GC’s and I know there’s a thing called HandleScope which ‘protects’ your local variables from the GC and updates them if a gc heap copy happens. For example, if I have a routine which adds togother 2 values and I call it, it may invoke the garbage collector which will copy the Object that my value is pointing to (or the GC will not even know that the Object the value is pointing to is referenced). A really minimal example:

#include <vector>

Value addValues(Value a, Value b);
std::vector<Value*> gc_vals_with_protection;

int func(Value a, Value b)
{
    vars.push_back(&a); // set protection for a
    gc_vals_with_protection.push_back(&b); // set protection for b
    Value res = addValues(a, b); // do calcuations
    gc_vals_with_protection.pop_back(); // remove protection for b
    gc_vals_with_protection.pop_back(); // remove protection for a
    return res;
}

But this has got me thinking, it will mean that a and b will NEVER be on the physical CPU registers because you have taken their addresses (and CPU registers don’t have addresses) which will make calcuations on them inefficient. Also, at the beggining of every function, you would have to push back twice to the vector (https://godbolt.org/z/dc6vY1Yc5 for assembly).

I think I may be missing something, as this must be not optimal. Is there any other trick I am missing?

Access elements from a function

I wanted to to know is there a way that I can access an element that was created from a function. I am trying to set a click event for every element created but I cant get it to work.
Thanks in Advance

function createDuck() {
  let newDuck = document.createElement("div");
  newDuck.classList.add("duck");
  randomPosition(newDuck);
  body.appendChild(newDuck);
  return newDuck;
};

const ducks = document.querySelectorAll("duck");
 
ducks.forEach(function (item) {  
  item.addEventListener("click", () => {
    item.classList.add("shot");
  });
 });

electron taking a long time to run

const {app, BrowserWindow} = require('electron') 
const url = require('url') 
const path = require('path')  

let win  

const createWindow = ()=> { 
    win = new BrowserWindow({
        width:800,
        height: 600,
        resizable: false   })
 
     win.loadFile('index.html')
 }  

app.whenReady().then(createWindow)

Then when I run I say electron main.js in the terminal and it takes for ever to load my window

Upload an input image taken from webapp into google drive with google script

I found something similar here, but it seems a lot more complicated than what I need.

I am uploading an image to a webapp and I would like to save the image into google drive.

I am having troubles to pass the file in a readable format for DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file); and I keep getting error. I do not know how to pass the file in the correct format.

HTML:

<input id = "output2" type="file" accept="image/*">
<script>
document.getElementById('output2').addEventListener('change', (e) => triggerF(e.target.files));

</script>


function triggerF(file) {

console.log("event triggered");
console.log(file.name);
google.script.run.withSuccessHandler(yourCallBack1).upload(file)}


function yourCallBack1() {
  console.log("callback called");
  }

GS:

function upload(e) {

const file = new Blob(e);
const filecreat = DriveApp.getFolderById("xxxxxxxxxxxxx").createFile(file);
console.log("created file");

}

How to get item data onclick if I render an array of objects?

Following issue:

I build an array of objects with specific data from a server, and I’d like to access the individual data. But obviously, the data gets lost once I’ve rendered the components. Any solutions on how to do something like this properly?

Array building of the components, objectsData contains the server response with all of the projects I’d like to render:

 const drawProjects = async () => {


    let i = 0;
    let projects = [];
    let searchedProjects = []
    if (search === '' || search === ' ') {
      while (i < objectsData[0].length) {
        projects.push(
            <SwiperSlide>
              <ProjectCard onClick={() => {
                setViewProjectDetails(true)
                setDetail(true)}}>
                <M2 src={m2}/>
                <Regulat>{objectsData[0][i].name}</Regulat>
              </ProjectCard>
            </SwiperSlide>
        );

        i++;

      }
      projectData.length = 0
      projectData.push(projects)
      console.log(projectData[0])
      setSearchTerm(search)

    } else {
      i = 0
      searchedProjects.push(filterByValue(objectsData[0], search))

      while (i < searchedProjects[0].length) {

        projects.push(
            <SwiperSlide>
              <ProjectCard onClick={() => {
                setDetail(true)
                setViewProjectDetails(true)

              }}>
                <M2 src={m2}/>
                <Regulat>{searchedProjects[0][i].name}</Regulat>
              </ProjectCard>
            </SwiperSlide>
        );
        i++;


      }
      projectData.length = 0
      projectData.push(projects)
      console.log(projectData)
      setSearchTerm(search)

    }

    setLoading(false)
    return projects;
  };

As you can see, I store the individual projects I’d like to render in the projectData array.

In my render I render it the following:

 <Swiper slidesPerView={calcSlides()} slidesPerGroup={calcSlides()} spaceBetween={30} navigation={{
                      prevEl: '.prev',
                      nextEl: '.next',
                    }}>
                      {projectData[0]}
                    </Swiper>

Now I’d like to get the id of the individual project which I click on. The id comes from the server and is with the entire project in the objectsdata array.

Any suggestions?

comparing two parameters of different races

I want to assign values to each race. Are my variables in the right position?

    function goodVsEvil(good, evil){

if (good > evil){
  const good = ["Hobbits", "Men", "Elves", "Dwarves", "Eagles", "Wizards"]
  const evil = ["Orcs", "Men", "Wargs", "Goblins", "Uruk Hai", "Trolls", "Wizards"]
  return string = "Battle Result: Good triumphs over Evil"
} else if (good < evil){
  return string = "Battle Result: Evil eradicates all trace of Good"
} else {
  return string = "Battle Result: No victor on this battle field" 
}
}

Slider has no height and doesn’t display unless I set hardcoded height

I’m trying to create a slider component from zeto to use on my project. The problem I’m currently facing is that the slider has 0 height unless I set hardcoded height like height: 50rem;. I can’t spot what’s cauising this or why.

You can find working code snippet here: https://jsfiddle.net/fj640arc/1/

You should remove height: 50rem; on .slider CSS class to see how it looks. I shouldn’t hardcode an height for sliders.

Also any help help would be appreciated on responsive images for this slider. How can I improve this slider images to be able to fit on the slider properly and not break it?

Thanks!

CSS SVGator animations and multiple classes

The premise:
There are 8 tabs (with JS) to toggle the associated content wrappers via display:none –> display:block. Those content wrappers have animated SVGs inside them and they cause issues.
Essentially, if the tab is active, the associated content wrapper should display and the SVG animation should play. Once another tab is activated, the previous content wrapper and the SVG animation should reset.

I’ve created some animations in SVGator, yet failed to put them to work due to a few reasons:

  1. Having 8 tabs, each containing only one of the 8 SVGs means only the active tab should animate. This is obviously not the case and they would all animate even if invisible.
  2. So I thought using the ‘scroll into view’ would fix it, coupled with switching of the tabs. However, since the tabs turn the SVG respective wrappers from display:none to display:block, the animations fail to play at all. (I’ve tried to research the keyframes and diplay:block properties for that matter…)
  3. So I thought I’d turn to CSS only animation, compile all keyframes into a .css file and would toggle the class to activate the respective keyframes.

Currently, I think that using the 3. approach is the only viable solution here. Yet, my JS is not strong and seemingly failed me somewhere =(
Could someone please help me fix it?
Bonus query: any other suggestions how this could be all put together to work?

<div class="taps">
     <button class="taplinks" onclick="openTap(event, 'One', SVG-1)" id="defaultOpen">Button 1</button>
     <button class="taplinks" onclick="openTap(event, 'Two', SVG-2)">Button 2</button>
     <button class="taplinks" onclick="openTap(event, 'Three', SVG-3)">Button 3</button>
   </div> 

   <div id="One" class="tapcontent">
      <svg id="SVG-1" . . .rest of the generated code (without CSS keyframes). . . </svg>
   </div> 
   <div id="Two" class="tapcontent">
      <svg id="SVG-2" . . .rest of the generated code (without CSS keyframes). . . </svg>
   </div> 
   <div id="Three" class="tapcontent">
      <svg id="SVG-3" . . .rest of the generated code (without CSS keyframes). . . </svg>
   </div> 


JavaScript: 

function openTap(evt, TapName, svgName) {
  var i, tapcontent, taplinks;
  tapcontent = document.getElementsByClassName("tapcontent");
  for (i = 0; i < tapcontent.length; i++) {
    tapcontent[i].style.display = "none";
  }
  taplinks = document.getElementsByClassName("taplinks");
  for (i = 0; i < taplinks.length; i++) {
    taplinks[i].className = taplinks[i].className.replace(" active", "");
  }
  document.getElementById(TapName).style.display = "block";
  evt.currentTarget.className += " active";
  var element = document.getElementById(TapName);
  element.classList.add("reveal");
}
document.getElementById(svgName).style.display = "block";
  evt.currentTarget.className += " active";
  var element = document.getElementById(svgName);
  element.classList.add("animate");
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

I’ve used this JS successfully without SVGs (used to be just images), so switching the tabs works, yet for some reason by adding the same logic to SVG element.classList.add(animate); doesn’t seem to work.
NB: I’ve renamed some of the parameters, as I tend to use weird to the outsiders logic and naming xD

How do you remove the last value in an array if it doesn’t match the first value in the next array?

I might not be asking the right question here.

I’m retrieving bookings that have the first night and last night date and I’m trying to display on a calendar which dates are not available.

In order to get a list of booked dates, I am doing the following:

const bookedDates = bedsData?.map(({ firstNight, lastNight }) => {
    const newArrivalDate = new Date(firstNight + "T00:00")
    const newDepartureDate = new Date(lastNight + "T24:00")

    var getDaysArray = function (start, end) {
      for (
        var arr = [], dt = new Date(start);
        dt <= end;
        dt.setDate(dt.getDate() + 1)
      ) {
        arr.push(new Date(dt).toDateString())
      }
      return arr
    }
    var daylist = getDaysArray(newArrivalDate, newDepartureDate)

    daylist?.map((v) => v)

    return daylist.join(", ")
  })

This returns

0: undefined
1: "Sat Feb 05 2022, Sun Feb 06 2022, Mon Feb 07 2022, Tue Feb 08 2022, Wed Feb 09 2022, Thu Feb 10 2022, Fri Feb 11 2022, Sat Feb 12 2022"
2: undefined
3: "Sat Feb 12 2022, Sun Feb 13 2022, Mon Feb 14 2022, Tue Feb 15 2022, Wed Feb 16 2022, Thu Feb 17 2022, Fri Feb 18 2022, Sat Feb 19 2022"
4: "Sat Feb 19 2022, Sun Feb 20 2022, Mon Feb 21 2022, Tue Feb 22 2022, Wed Feb 23 2022, Thu Feb 24 2022, Fri Feb 25 2022, Sat Feb 26 2022"
5: undefined
6: undefined
7: "Sat Feb 26 2022, Sun Feb 27 2022, Mon Feb 28 2022, Tue Mar 01 2022, Wed Mar 02 2022, Thu Mar 03 2022, Fri Mar 04 2022, Sat Mar 05 2022"
8: "Sat Mar 05 2022, Sun Mar 06 2022, Mon Mar 07 2022, Tue Mar 08 2022, Wed Mar 09 2022, Thu Mar 10 2022, Fri Mar 11 2022, Sat Mar 12 2022"
9: undefined
10: undefined
11: "Fri Mar 25 2022, Sat Mar 26 2022, Sun Mar 27 2022, Mon Mar 28 2022, Tue Mar 29 2022"

To show which dates are booked I’m am using

if (bookedDates.join().includes(calDates)) {
    style.textDecoration = "line-through"
    style.color = "rgba(0, 0, 0, 0.25)"
}

calendar showing bookedDates / available dates

The issue I’m facing is with dates that don’t have a check out and check in on the same day. The “last day” and the “first day” of the next booking are still being included in the list of “bookedDates”. However, they need to be “available” to check out or check in still.

I hope that makes sense… pretty lost with this one!

Thanks

Unsure if this is breadth first or depth first search?

I’m reviewing bfs and dfs concepts and recently wrote this search method for a Trie tree. I believe it is bfs because we’re searching each level starting from the root if the next value exists. I’m not sure what implementing dfs would look like in a problem like this. I could be completely wrong though.

class TrieTree {
  constructor() {
    this.root = new TreeNode();
  }
  insert(word) {
    let currentNode = this.root;
    for (let char of word) {
      if (currentNode.children.has(char)) {
        currentNode = currentNode.children.get(char);
        continue;
      } else {
        currentNode.children.set(char, new TreeNode(char));
        currentNode = currentNode.children.get(char);
      }
    }
    currentNode.isWord = true;
  }
  //I'm not sure if this should be called bfs or dfs
  bfs(searchTerm) {
    let currentNode = this.root;
    for (let char of searchTerm) {
      if (currentNode.children.has(char)) {
        currentNode = currentNode.children.get(char);
      } else {
        return false;
      }
    }
    return true;
  }
}

class TreeNode {
  constructor(val) {
    this.data = val;
    this.children = new Map(); //collection of nodes in TS we would use TreeNode[];
    this.isWord = false;
  }
}

let tree = new TrieTree();

tree.insert("hello");
tree.insert("bucky");
tree.insert("hell");

console.log(tree.bfs("bucky"));

Simple JS program 3 item with negative and positive click boxes and total

Just started to learn javascript. I have a simple school project. I have 3 items with – and + buttons with total for each and then final total for all 3. I can’t get the total button to not go below 0. It goes to negative values. The other 3 don’t drop below 0 in their individual total count.

//set default values

let gb = 0 // Gingerbread
let cc = 0 // Chocolate Chip
let ss = 0 // Sugar Sprinkle
let total = 0

//set variables for quantity

var totalQuantity = document.getElementById('qty-total');
var gbQuantity = document.getElementById('qty-gb');
var ccQuantity = document.getElementById('qty-cc');
var ssQuantity = document.getElementById('qty-sugar');
//set event listener for Gingerbread cookie + button
document.getElementById("add-gb").addEventListener("click", function(e) {
{
    gb++
}
gbQuantity.textContent = gb;
total = total + 1;
totalQuantity.textContent = total;
console.log("Gingerbread + was clicked!")
})

// set even listener for Gingerbread cookie - button
document.getElementById("minus-gb").addEventListener("click", function(e) {
if(gb > 0)
{
     gb--
} 
   
gbQuantity.textContent = gb;

total = total - 1;
totalQuantity.textContent = total;
        
console.log("Gingerbread - was clicked!")
})

//set event listener for Chocolate chip cookie + button

document.getElementById("add-cc").addEventListener("click", function(e) {

{
    cc++
}

ccQuantity.textContent = cc;

total = total + 1;
totalQuantity.textContent = total;

console.log("Chocolate Chip + was clicked!")
})

//set event listener for Chocolate chip cookie - button

document.getElementById("minus-cc").addEventListener("click", function(e) 
{
if(cc > 0)
{
    cc--

}
    
ccQuantity.textContent = cc;
total = total - 1;
totalQuantity.textContent = total;

console.log("Chocolate Chip - was clicked!")
})

//set event listener for Sugar Sprinkle cookies + button

document.getElementById("add-sugar").addEventListener("click", function(e) {

{
    ss++
}

ssQuantity.textContent = ss;
totalQuantity = document.getElementById("qty-total");
total = total + 1;
totalQuantity.textContent = total;

console.log("Sugar Sprinkle + was clicked!")
})

//set event listener for Sugar Sprinkle cookies - button

document.getElementById("minus-sugar").addEventListener("click", function(e) {
if ( ss > 0)
{
    ss--
}    

ssQuantity.textContent = ss;

total = total - 1;

totalQuantity.textContent = total;

console.log("Sugar Sprinkle - was clicked!")
})

So the total quantity keeps dropping below 0 after the minus buttons are still clicked. Thank you for any assistance.

How to use a variable inside setAttribute?

So this should return a grid size of whatever the user inputted.

So for example if i input 13×13 it should give me a 13×13 grid, the only problem i have is idk know the grid size and i cant do grid-template-columns: repeat(x, 1fr) and obviously same with grid-template-rows

How to access dynamically created buttons in angular?

So, I am creating a quiz application where I have a scrollbar for questions and in that scrollbar I have buttons depending on the length of a question set. So I’ve created those buttons using *ngFor directive. Now what I want to do is whenever a user selects any option (mcq), the question buttons in the scrollbar should get highlighted in following way:

  1. If user selects any option, then change the question button color to Green
  2. If user skips the question, then change the question button color to Yellow

HTML Code for Question Scrollbar:

<div id="answer-buttons" class="ques-grid ">
            <button #navBarButton *ngFor="let item of items">{{item}}</button>
</div>

I’m have tried doing it by first accessing the buttons using ViewChild in ts file and then apply some logic, but it’s not working, it is only changing the color of first button

@ViewChild('navBarButton',{ static: false }) navBarButton:ElementRef
//and in some function I've tried this logic
if(this.attemptedQuestionCount[this.currentQuestionIndex]==1){
  this.navBarButton.nativeElement.style.backgroundColor = "#228B22"
}
else{
  this.navBarButton.nativeElement.style.backgroundColor = "#FCF55F"
}

How can I achieve my objective?