addEventListener from bindEvents method in OOP doesn’t work

I currently work on a school project with JS and I need to etablish a modal and a lightbox in the same page.
I work with classes and when I initialize my Lightbox and Modal classes, only one of them works.
That is, the methods called when initializing my classes work but the bindEvents method containing my addEventListener doesn’t work.

Here are more details :

My Controller class

class Controller {
  init = () => {
    ...
    
    Modal.init()
    Lightbox.init()
  }
}

My Modal class

class Modal {
  init = () => {
    // ...

    this.bindEvents()
  }

  bindEvents = () => {
    const openBtn = document.querySelector('.modal-btn')
    // ...

    openBtn.addEventListener('click', this.open)
    // ...
  }

  open = () => {
    // Open modal function
  }
}

export default new Modal()

My Lightbox class

class Lightbox {
  init = () => {
    // ...

    this.bindEvents()
  }

  bindEvents = () => {
    const openBtn = document.querySelector('.lightbox-btn')
    // ...

    openBtn.addEventListener('click', this.open)
    // ...
  }

  open = () => {
    // Open lightbox function
  }
}

export default new Lightbox()

The only class whose events work is the last to be called, so Lightbox in this example.

I also want to clarify that I work with native JavaScript and that each of my two classes work, the problem remains with the events of the first class called which do not work.

Thanks for taking a look, I think I’ve tried almost everything!

Unable to edit data on the same view page laravel

I want to update the business hour on the same page. There are other answer that I review in the stackoverflow but I still cannot manage. Help really appreciated.

Model


namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Hour extends Model
{
    public $table = 'biz_hour';
    protected $primaryKey = 'day_id';
    protected $fillable = [
        'day_id', 'day_name', 'start_time', 'end_time', 'day_off'
    ];
    public $timestamps = false;

}

Controller

public function update(Request $request, Hour $biz_hour)
    {
        
        $request->validate([
            'start_time' => 'required',
        ]);
    
        $start_time = AppModelsHour::find($biz_hour);
    
        ['start_time' => $request->start_time];
        foreach($biz_hour as $biz_hour){
        $start_time->save();
        }
        return redirect('start_time');

        //$biz_hour->update($request->all());
        //return redirect()->route('biz_hour.index');
    }

Biz_hour.blade.php

<div class="table-responsive">
                        <table class="table">
                            <thead class="text-uppercase">
                                <tr>
                                    <th scope="col">Day</th>
                                    <th scope="col">Start Time</th>
                                    <th scope="col">End Time</th>
                                    <th scope="col">is Day off?</th>
                                </tr>
                            </thead>
                            @foreach($biz_hour as $biz_hour)
                            <form action="{{ route('biz_hour.update',$biz_hour->day_id) }}" method="POST">
                                @csrf
                                @method('PUT')
                            <tbody>
                                <tr>
                                    <th scope="row"><br>{{$biz_hour->day_name}}</th>
                                    <td><div class="form-group">
                                        <input class="form-control" type="time" value={{ Carbon::parse($biz_hour->start_time)->format('h:i') }} name="start_time"></div>
                                    </td>
                                    <td><div class="form-group">
                                        <input class="form-control" type="time" value={{$biz_hour->end_time}} name="end_time"></div>
                                    </td>
                                    <td><br><label class="switch">
                                        <input type="checkbox">
                                        <span class="slider round"></span>
                                      </label></td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>    
                <div class="main-content-inner">
                    <div class="col-lg-6 mt-5">
                        <button type="submit" class="btn btn-primary mb-3" name="upload">Save</button>
                    </div>
                </div>
            </form> 

After clicking save button, the page only refresh but the data is not sent to the database. Thanks in advance.

Replace selector with array item

I would like to archive that I have an Array, with 3-4 Items and then I want to itterate throw all of them and change the selector in the function with the items of the array.

let items = ['Name','Person,'New']

then my function

$('.btn').on("click", function(){do smth});

and then the foreach .btn should be like name or person, and I want maybe to add late more Items to the array. How should I do it?

why TODO list is not working properly in reactjs

import React from 'react'
const Todo = () => {
    const[newitem,setNewitem]=React.useState("");
    const [list,setList]=React.useState([]);
    function addItem(todovalue)
    {
        if(todovalue!=="")
        {
            const newItem={
                id:1 + Math.random(),
                value:todovalue,
                isDone:false
            }
            const list=[...list];
            list.push(newItem);
            setNewitem({list,newItem:""});
        }
    }
    function deleteItem(id)
    {
        const list=[...list];
        const updatedlist=list.filter(item=>item.id!==id);
        setNewitem({updatedlist});
    }
    function update(input)
    {
        setNewitem({newItem:input});
    }
    return (
        <div className="container">
           
            <h1>Add an item...</h1>
            <input type="text" placeholder="add item" required value={newitem} onChange={e=>update(e.target.value)}/>
            <button clasName="add-btn" onClick={()=>addItem(newitem)} disabled={newitem.length}>Add Todo</button>
            <div className="list">
                <ul>
                    {
                        list.map(item=>{
                            return(
                                <li key={item.id}>
                                    <input type="checkbox" checked={item.isDone} onChange={()=>{}}/>
                                    {item.value}
                                    <button className="btn" onClick={()=>{deleteItem(item.id)}}>Delete</button>
                                </li>
                            )
                        })
                    }
                </ul>
            </div>

            
        </div>
    )
}

export default Todo
when we going to write some text in text field it get only [object Object] and when we click on Add Todo button its throws error “Cannot access ‘list’ before initialization” how to resolve that one

How to get a different return type according to the object accessing key?

Let me simply put it like,

interface PlanValue {
  planName: string;
  startDate: string;
} 

type DeviceKey = 'pc' | 'mobile' | 'laptop';

type PlanType = Record<DeviceKey, PlanValue>

interface Subscription {
  valid: boolean;
  plan: PlanType;
}

Let’s say that a new device key called Kiosk is added to DeviceKey type.

But the return type of this key should be boolean.

For example

const subsc1: Subscription = new Subscription();
const subsc2: Subscription = new Subscription();
console.log(subsc1.plan.pc)    // type should be PlanValue
console.log(subsc2.plan.Kiosk) // type should be boolean

I can’t change the Subscription.plan type to PlanType | boolean because it will break other codes that are referring to this type.

How can I get a different return type according to the accessing key during the runtime?

Issue in applying margin using angular “data-ng-style”

There is <li> element in HTML that is calling a JS method “SiteAssetStyleForShiftedAsset” like this

<li class="holder-white title-holder" data-ng-style="{{SiteAssetStyleForShiftedAsset()}}" data-ng-click="getSiteAssetDetailByAssetId(asset.id,asset.assetId,asset.jobPlantId, asset.siteAssetId, asset.uniqueKey, asset.plantId,asset.siteAssetGuidId);">

Inside JS we defined that method like this:

$scope.SiteAssetStyleForShiftedAsset = SiteAssetStyleForShiftedAsset;
function SiteAssetStyleForShiftedAsset() {

    var isPPMJob = localStorage.getItem("IsPPMJob").toUpperCase();

    var shiftingAsset = $scope.addClassForShiftingAsset;

    if (isPPMJob == "FALSE") {
        return { "margin-right": "50px" };
    }
    else if (isPPMJob == "TRUE") {
        if (shiftingAsset == true || shiftingAsset == "true") 
        {
            return { "margin-right": "50px" };
        }
        else {
            return { "padding-right:": "15px" };
        }
    }
}

In outer If condition that states “if (isPPMJob == “FALSE”)” margin is applying perfectly fine
But when condition become “TRUE” in “else if (isPPMJob == “TRUE”)” it isn’t applying margin.
However alerts in all statements are working. Only problem with applying margin.
I have also inspected the element and it was showing data-ng-style=”{“margin-right”:”50px”}” but on the view nothing was changed.

How to refresh the data displayed by the JavaScript page provided by thymeleaf and spring boot

I have a backend written in spring boot that consumes two external APIs, processes them writes them to a DTO, and then through a controller injects them into the frontend. My site marks the location of planes on a map. The location changes every 1s, so I would like the planes on my site to refresh every 1s as well. The site does not provide Web Socket, but it is possible to call API every 2s. I set Scheduler but even when data was fetched from API, it was not refreshing automatically on my frontend.
Demo site

My Controller code:

@Controller
@AllArgsConstructor
public class AirplaneController {

private final AirplaneService airplaneService;

@GetMapping("/index")
public String getIndex(Model model) throws IOException {
    model.addAttribute("airplanes", airplaneService.getAirplanes());
    return "map";
}
}

My index JS:

    var map = L.map('map').setView([52.95, 19.23], 7);
var ciLayer = L.canvasIconLayer({}).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var airplanes = [[${airplanes}]];

var icon = L.icon({
iconUrl: 'plane.png',

iconSize:     [15, 15], // size of the icon
iconAnchor:   [15, 15], // point of the icon which will correspond to marker's location
popupAnchor:  [-10, -10] // point from which the popup should open relative to the iconAnchor
});

airplanes.forEach(value => {
    var temp =L.marker([value.latitude, value.longitude], {icon: icon}).addTo(map).bindPopup("Flight " +value.callsign+" from "+value.origin_country);
    temp.setRotationAngle(value.heading);
})

Why does html2canvas leave gaps between divs which butt together?

In this example, I’m using background images in the outside divs in a 3×3 grid of divs.
There is no border or margin between the divs, and the HTML output seems fine.

However, when I convert this to an image, using html2canvas, the resulting image shows transparent lines between the divs. Almost like there is a single pixel margin on each div.

Am I doing something wrong, or is this a bug in html2canvas?

https://jsfiddle.net/Onefunction/abry3x67/

NB, I have raised an issue in html2canvas’s github

EDIT For some reason, I have to add code here, even though it’s all on jsfiddle.
so here’s the javascript i used…

html2canvas(document.querySelector(".ttable"), {
                    scrollX: -window.scrollX,
                    scrollY: -window.scrollY,
                    backgroundColor: null,
                    allowTaint: true,
                    useCORS: true,
                    // logging: true,
    }).then((generatedImage) => {
  jQuery(".ttable-image").html(generatedImage);
  
    });
})```

How can I get any Json object to the javascript lambda aws sdk?

Just started using AWS, and I’m trying to create a lambda function using javascript that I call the JSON objects in there.
To do that it’s used JSON.parse() to convert a JSON object or string into a Javascript object.
Example:

let s = '{"hello":"world"}';
let obj = JSON.parse(s);

But what I’m trying to do is to call any JSON object and not to declare with the let function, but to call any object that is on JSON.
Would appreciate any response

Thank you!

Hashing using pbkdf2 returns different results despite the same salt

I tried to hash password 1000 times. Then hash the result again, but I get a different final result than password hashed 1001 times despite having the same salt

import {pbkdf2Sync} from "pbkdf2";

const hash = (password: string, iterations: number) => {
    const salt = "salt"
    let hashedNTimes = pbkdf2Sync(password, salt, iterations, 64, 'sha256')
    let hashedNTimesAndOnceAgain = pbkdf2Sync(hashedNTimes, salt, 1, 64, 'sha256')
    let hashedNPlus1Times = pbkdf2Sync(password, salt, iterations + 1, 64, 'sha256')

    console.log(hashedNTimes.toString('hex'))
    console.log(hashedNTimesAndOnceAgain.toString('hex'))
    console.log(hashedNPlus1Times.toString('hex'))
}

Object.create and delete property from newly created object

If Object.create makes new deep copy of the object, what should happen post deleting the property from the newly created object?

Expected Output: Undefined

Actual Output: Karna

Code

var obj1 = {name:"Karna",loc:"Bengaluru"};

var obj2 = Object.create(obj1);

delete obj2.name;

console.log(obj2.name);

Could you please help me to understand why obj2.name still referring to obj1’s property?

Clearing Cache in PWA

I want to develop an offline capable progressive web application.

Looking into an example of such an app – airhorner I find that it uses specific version of the application to make sure correct version is loaded.

https://github.com/GoogleChromeLabs/airhorn/blob/main/app/sw.js#L21

However what happens with older version? Do I need to cleanup it? My app is rather large because it contains lots of data (html+js ~1.5MB) and from what I read on iOS there is limit of 50MB of cache per app.

So I wonder if I need to make sure I remove cache of older versions or I can just assume it is cache and it will be removed because it is too old?

if I do need to remove older version, where is the correct place to call it?

I see in https://stackoverflow.com/a/45468998/66522 that it is called for activate event. Can I just add another event listener on this event in addition to this one? https://github.com/GoogleChromeLabs/airhorn/blob/main/app/sw.js#L40

Why are images not pulling up in popup HTML window even though they work in main HTML window?

I have a Robot Framework test that generates a pop-up HTML report. Right now I’m just testing against a image/video database. Here is a screen grab.

enter image description here

The issue is the images. That link is supposed to navigate to the image. No dice. A thumbnail is supposed to be in that 50×50 square. I can inspect the code, see that the URL is right and even verify the image exists at that location.

enter image description here

When I follow the link, I get this blocked message. No idea why.

enter image description here

I tried it in multiple browsers, so it has to be the way I’m dynamically building the page.

enter image description here

All I’m doing is taking the image file URL from the Robot Framework test results and creating some HTML text in the new window. Later that get’s put into the table in lieu of text or other data. I tried that same approach on the parent window and it works fine.

enter image description here

enter image description here

Why isn’t the image loading in the popup?

How to put 2 javascript items on 1 line?

I’ve been creating a JS website where it tells you your age in days. I wrote the code, so that, if you were born before 1990, the website says “Yikes you’re old”. I styled that text apart from the other text but the output was on another line. I want to bring both texts on the same line. I don’t know how to do that, so your help is greatly appreciated. Here’s the JS code:

function ageInDays() {
  // variables
    var birthYear = prompt("What Year Were You Born In?");
    var ageInDayss = (2021 - birthYear) * 365;

  //text

    if (birthYear>1990) {
        var h1 = document.createElement('h1');
        var textAnswer = document.createTextNode("You are " + ageInDayss + " days 
        old.");
        h1.setAttribute('id', 'ageInDays');
        h1.appendChild(textAnswer);
        document.getElementById('flex-box-result').appendChild(h1);

   } else {
       var h1 = document.createElement('h1');
       var h2 = document.createElement('h2');
       var textAnswer = document.createTextNode("You are " + ageInDayss + " days old.");
       var textAnswer1 = document.createTextNode(" Yikes... that's old.");
       h1.setAttribute('id', 'ageInDays');
       h2.setAttribute('id', 'yikes');
       h1.appendChild(textAnswer);
       h2.appendChild(textAnswer1);
       document.getElementById('flex-box-result').appendChild(h1).appendChild(h2);
    }


}

How do I bring the “else” output on one line?