Can see ‘backgroundImage’ under element’s style object, but `style.backgroundImage` isn’t working pulling anything

I’m working in this very old application that relies pretty heavily on jQuery.

What I am trying to grab is this specific elements background image. I can log the entire DOM element and clearly see that backgroundImage has a value, the URL is correct, and I know that that is exactly what it should be giving me.

However, when I go get that value I get nothing. I can’t log it into the console or anything. Is there something very specific I need to be doing? I feel like this should be pretty simple: if I can see the element and log it, I should be able to grab anything from it.

I’m traversing up the DOM with .parents() and grabbing the correct element, then trying to put the background image of that element into a variable with element.style.backgroundImage but nothing is happening.

Can’t log it and no errors. Am I doing something very wrong here? I haven’t found anything specific to this problem.

Thanks!

Format non nested object to nested object in JavaScript

We get a non nested object

obj = {
        "your-email": "[email protected]",
        "prename": "Jane Doe",
        "service__1": "Google",
        "login__1": "[email protected]",
        "password__1": "PW1",
        "service__2": "Microsoft",
        "login__2": "[email protected]",
        "password__2": "PW12!",
        "service__3": "Stackoverflow",
        "login__3": "[email protected]",
        "password__3": "3PW2!",
        "DPA": "1"
    }

We would like to transform this object into following structure:

nestedOBJ =         
{
        "your-email": "[email protected]",
        "prename": "Jane Doe",
        "DPA": "1",
        "service1": 
                  {
                    "service__1": "Google",
                    "login__1": "[email protected]",
                    "password__1": "PW1"
                  },
        "service2": 
                  {
                    "service__2": "Microsoft",
                    "login__2": "[email protected]",
                    "password__2": "PW12!"
                  },
        "service3": 
                  {
                    "service__3": "mySQL",
                    "login__3": "[email protected]",
                    "password__3": "3PW2!"
                  },
        "service4": 
                  {
                    "...":"..."
                  }
}

The following code has been tried without success:

let res = {}
let length = Object.keys(obj).length -3;
for (let i = 0; i < length  ; i + 3){
console.log(steps.trigger.event.body[0]["service__"+i])
  let onestedOBJ = {
    ["creds"+i]:steps.trigger.event.body[0]["service__"+i],
    ["creds"+i]:steps.trigger.event.body[0]["login__"+i],
    ["creds"+i]:steps.trigger.event.body[0]["password__"+i]
  }  
console.log(nestedOBJ)
}

We didn’t include the DPA, your-email and prename. Because the for loop didn’t even work.

how to bind data in material-ui using redux hooks

I am using material-UI and redux in react I am using first-time redux so I am confused about how to implement it with my list items.

here is my code of product.js and I am successfully getting data in my redux store, I will show you below

const dispatch = useDispatch(); 

const {loading, product, error, productCount} = useSelector(state => state.products);
console.log(loading)
console.log(product)
console.log(error)
console.log(productCount)


useEffect(()=>{
      const data =  dispatch(getProducts());
      console.log(data)
},[dispatch])

here is my code of table

<TableContainer component={Paper}>
<Table sx={{ minWidth: 500 }} aria-label="custom pagination table">
  <TableBody>
    {(rowsPerPage > 0
      ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
      : rows
    ).map((row) => (
      <TableRow key={row.name}>
        <TableCell component="th" scope="row">
          {row.name}
        </TableCell>
        <TableCell style={{ width: 160 }} align="right">
          {row.calories}
        </TableCell>
        <TableCell style={{ width: 160 }} align="right">
          {row.fat}
        </TableCell>
      </TableRow>
    ))}

    {emptyRows > 0 && (
      <TableRow style={{ height: 53 * emptyRows }}>
        <TableCell colSpan={6} />
      </TableRow>
    )}
  </TableBody>
  <TableFooter>
    <TableRow>
      <TablePagination
        rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
        colSpan={3}
        count={rows.length}
        rowsPerPage={rowsPerPage}
        page={page}
        SelectProps={{
          inputProps: {
            'aria-label': 'rows per page',
          },
          native: true,
        }}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
        ActionsComponent={TablePaginationActions}
      />
    </TableRow>
  </TableFooter>
</Table>

if I show to my redux data so I am receiving data on this page
enter image description here

here is my console image
enter image description here

I hope it will be enough code to describe my problem but if anyone want to see further code to understand my problem so i will provide it

React-native-vision-camera can’t access to normal camera in back

i am trying to use ‘normal’ camera on my iphone 11 pro.
I use react-native-vision-camera.
When i run this code:

  const devices = useCameraDevices();
  const deviceBack = devices.back;
  console.log(deviceBack?.devices)

I get only 2 cameras : ["ultra-wide-angle-camera", "wide-angle-camera"], I don’t want a wide camera, I want to access to my normal camera, how to do it ?
Thanks.

Where am I having errors with this Switch control structure in JS?

I am working on a function using Javascript that according a received value (a mark) returns to you the qualification of this mark, according to the Spanish educational system. The code is the following one:

function calculateSpanishClassAverageMark(averageMark) {
    console.log("me muestra mi nota media", averageMark);
    var markText = " ";

    switch (averageMark) {
        case 10:
            markText = "Esta clase ha obtenido una matrĂ­cula de honor"
            break;
        case averageMark >= 9 && averageMark < 10:
            markText = "Esta clase ha obtenido un sobresaliente"
            break;
        case averageMark >= 7 && averageMark < 9:
            markText = "Esta clase ha obtenido un notable"
            break;
        case averageMark >= 6 && averageMark < 7:
            markText = "Esta clase ha obtenido un bien"
            break;
        case averageMark >= 5 && averageMark < 6:
            markText = "Esta clase ha obtenido un suficiente"
            break;
        case averageMark >= 4 && averageMark < 5:
            markText = "Esta clase ha obtenido un insuficiente"
            break;
        case averageMark < 4:
            markText = "Esta clase ha obtenido un muy deficiente"
            break;
        default:
            break;
    }

    return console.log("Marktext", markText);
}

The first console.log shows me muestra mi nota media 7.625so the averageMark parameter is being received. However, the console.log that I return shows the following stuff: Marktext . I have tried to debug, and the behavior is that when the program gets to the switch, it goes directly to the default option, so it does not change the value of markText. Where am I making an error? I dont understand why if the averageMark value is 7.625, why it doesnt enter in that case of the switch. Thanks.

Blurry result depending on server the app is served with

When I server the app from this repo with live Server I get a neat

enter image description here

But If I serve it with node const server = http.createServer((req, res) => {...} code in the index.js file, I get this blurred result.

enter image description here

I tried also with an static server with the same result (commented in the index.js codein the repo)

var file = new(static.Server)(__dirname);

http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(8000);

In the screenshots might not be that clear, but when the app runs in the browser the difference is huge. I think there should be some step in the serving process that I am missing.

Thanks in advanced for any idea.

Angular modal is closing when clicking at the backdrop and at the content

I have created a small Angular component called Modal to use it as a modal on my app. The modal opens when clicking on a button on the page and should close when clicking on the backdrop or a cancel button.

Now is opening when clicking on the button on the page (good) and closing when clicking on the backdrop (good) my issue is that is closing when I click on the content (bad).

To manage when the modal is open or close I’ve defined a variable on the page controller that starts at false and when clicking on the button switches to true and shows the modal. When clicking on the backdrop the same function switches back the variable to false.

This is my board-page.component.ts:

export class BoardPageComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}

  isModalShown: boolean = false;

  newTask() {
    console.log(`Click Modal!`);
    this.isModalShown ? this.isModalShown = false : this.isModalShown = true;
  }
}

This is the board-page.component.html:

<app-modal *ngIf="isModalShown" (close)="newTask()">
  <h1>Modal Content</h1>
</app-modal> 

And this is the modal component modal.component.ts:

export class ModalComponent implements OnInit {
  @Output() close = new EventEmitter();

  constructor() {}

  ngOnInit(): void {
  }

  onClose() {
    this.close.emit();
  }
}

And the modal.component.html

<div class="modal-backdrop" (click)="onClose()">
  <div class="modal-content" id='modal'>
    <ng-content></ng-content>
  </div>
</div>

I’ve placed the click event on the backdrop, but seems that when clicking on the content the click event fires thou the z-index is higher. When the click events are fired emits to the function in the parent component that updates the isModalShown value.

And the styles that make the backdrop and content effect:

.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 20;
  background-color: rgba(0, 0, 0, 0.75);
}

.modal-content {
  position: fixed;
  top: 15vh;
  left: 5%;
  width: 90%;
  background-color: white;
  padding: 1rem;
  border-radius: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
  z-index: 30;
  animation: slide-down 300ms ease-out forwards;

  pointer-events: none;
}

@media (min-width: 768px) {
  .modal-content {
    width: 40rem;
    left: calc(50% - 20rem);
  }
}

@keyframes slide-down {
  from {
    opacity: 0;
    transform: translateY(-3rem);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

I guess I should disable the click events on the content? I’ve tried with this:

document.getElementById('modal').addEventListener('click', (event) => {  
  event.preventDefault();  
});

But didn’t work.

I did not find a lot of examples to do this modal without 3rd party libraries.

I have used google places api for address suggestion, but on change of country it shows me dual suggestion on address, previous and current

I have used google places api for address suggestion. From country drop down i am selection country and passing it to “component restriction” in google places to restrict the address suggestion. Everytime when i change the country from dropdown, it showed me dual suggestions. Please help me to resolve the issue?

Thanks in advanced.

enter image description here

Here is my code

var initAutocomplete = (() => {
var autocomplete = null
var countryInput = document.getElementById('country')
var address1Field = document.getElementById('address')

var ISOCountry = 'US';
function handleCountryChange(event) {
    ISOCountry = event.target.value
    console.log(ISOCountry);
    autocomplete = new google.maps.places.Autocomplete(address1Field, {
        componentRestrictions: { country: ISOCountry },
        fields: ["address_components", "geometry"],
        types: ["address"]
    })
    autocomplete.addListener("place_changed");
}
countryInput.addEventListener('change', handleCountryChange)

return function initAutocomplete() {
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('address')), {
        types: ['geocode'],
        componentRestrictions: { country: ISOCountry }
    });
    autocomplete.addListener("place_changed");
}

})

How to handle when two nested Context providers are used in App.js file, each without one inside other will result in error

In this below code I need ThemeState to come over the AlertState, but if I do that, then I get the same error as what I am getting now. So how to handle this type of code.

import "./App.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import About from "./components/About";
import { Navbar } from "./components/Navbar";
import { Home } from "./components/Home";
import NoteState from "./context/notes/noteState";
import { Alert } from "./components/alert";
import Login from "./components/Login";
import SignUp from "./components/SignUp";
import AlertState from "./context/notes/alertState";
import { ThemeState } from "./context/notes/ThemeContext";

function App() {
  return (
    <>
      <NoteState>
        <AlertState>
          <ThemeState>
            <Router>
              <Navbar />
              <Alert message={null} />
              <div className={`my-2 text-dark bg-light`}>
                <Routes>
                  <Route exact path="/" element={<Home />} />
                  <Route exact path="/about" element={<About />} />
                  <Route exact path="/signup" element={<SignUp />} />
                  <Route exact path="/login" element={<Login />} />
                </Routes>
              </div>
            </Router>
          </ThemeState>
        </AlertState>
      </NoteState>
    </>
  );
}

export default App;

This is the error I am getting now and if I swap those two position I get the same error

cannot destructure property ‘setmsg’ of ‘(0,react__webpack_imported_module_0__.usecontext)(…)’ as it is undefined.

Editing Manifests for Firefox Add-Ons

I use a fairly popular add-on for firefox that changes my home page to a photo from google earth, but I hate how firefox attempts to show the add-ons name as part of the search bar on each new page. It’s too long a name to fit in the provided space, so it just shows as a garbled mess like, “Goo..EarthVi.” I just want to edit the add-ons manifest.json to shorten its title to “EarthView” so it hopefully fits in the add-on indicator in the search bar … which seemed easier than it’s been in practice.

(I’m not super familiar with JS or Java. I used VSCode as my IPE to edit files directly.)

Changing the manifest.json corrupts the add-on, which I think has to do with it no longer matching the hashes provided in the manifest.mf file in META-INF, so I used powershell to grab the 40 character SHA1 hash of my modified .json file only for that hash to be different from the hash-digests provided in manifest.mf

Name: manifest.json
Digest-Algorithms: MD5 SHA1
MD5-Digest: sEp1Fj2LQxivX8gRp/XclQ==
SHA1-Digest: 8TVzp9sQ5YN7ctlFbbvs5JgtNQY=

Default select option based on current year

I need a JS that autoselect as default option the current year from this select-dropdown.
Now we are in 2022, so the defaul option must be 2022.

Thanks.

<select id="yearDP">
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2022">2023</option>
<option value="2022">2024</option>
<option value="2022">2025</option>
<option value="2022">2026</option>
</select>

Why only one value of the tittle after clicking dynamic button

I work with Google Books Api and display card with books and creating them dynamic in js with button like this:

$.ajax({
            url: "https://www.googleapis.com/books/v1/volumes?q=subject:fiction",
            dataType: "json",
    
            success: function(data) {
                for (i = 0; i< 20; i++){
                    const content = `
                    <div class="card my-3" style="width: 18rem;">
                    <img class="mx-auto card-img-top book-cover imgs thumbnail" src="${data.items[i].volumeInfo.imageLinks.thumbnail}" style="width:170px; height:230px;" alt="">
                    <div class="card-body" id="results">
                        <h5 class="card-title" style="font-weight:bold">${data.items[i].volumeInfo.title}</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <div class="d-flex">
                        <div class="dropdown " style="margin-right:8px;">
                            <button class="btn btn-dark dropdown-toggle" 'type="button" style="height:2.5rem;" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Add
                            </button>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenu2">
                            <button class="dropdown-item iWantToRead" id = "iWantToRead" value='${data.items[i].volumeInfo.title}' type="button">I want to read</button>
                            <button class="dropdown-item" type="button">Read</button>
                            <button class="dropdown-item" type="button">I want to buy</button>
                            </div>
                        </div>                        
                        <button type="button" name="add_review" id="add_review" class="btn btn-dark">Review</button>
                        <a href="${data.items[i].accessInfo.webReaderLink}" class="btn mx-auto btn-dark" style="height:2.5rem;">Read</a>
                        </div>
                    </div> `;
                    card.innerHTML += content;

and I went to attach tittle of the book to button and depending what btn user click the tittle will display. But I am having problem that I am only getting tittle of first book no matter what btn I click

$('.iWantToRead').unbind().click(function(){
                        var button = document.getElementById('iWantToRead');
                        var tittle = button.getAttribute('value');
                        var thumbnail = button.getAttribute('data-value');
                        $.ajax({
                            type: "POST",
                            url: "bookshelf.php",
                            data: 
                            {
                                action:'iWantToRead',
                                tittle: tittle,
                                thumbnail: thumbnail
                            },
                            success: function(html){    
                                console.log(html);
                                
                            }
                        })
                    });

How to access a variable from outside of Ajax code [duplicate]

I would like to make fileContent variable available outside of $.ajax code.

var fileContent = "";

$.ajax({
method: "POST",
url: "php/somefile.php",
data: {"nazwaProduktu": "nazwa produktu"},
}).done(function( data ) {
        var result = $.parseJSON(data);
        if (result!== null){
            var len = result.length;
                for(var i=0; i<len; i++){
                    fileContent=fileContent+result[i].nazwa+";";
                    fileContent=fileContent+(result[i].komentarz)+"n";
                }
            }
        }
);

console.log(fileContent); //here I see fileContent empty! I need to have it updated by the above code.

Can you please advice how can I do this?

How can i store a selected in sessionStorage javascript?

im trying to store the <iput type='radio'/> that the user choose in sessionStorage…

in sessionStorage it should look like this:
key: user option.
value: option that user choose

i tried like this:

  const store = document.getElementById('rb');
  sessionStorage.setItem('user-selected-option', store.value);

but didn’t work

im pretty stuck right now, can you guys help me with this?

heres my code:

html:

<section>
        <label id="rb">select your option</label>
        <label id="rb">
          <input type="radio" name="options" value="1" />one</label>
        <label id="rb">
          <input type="radio" name="options" value="2" />two</label>
        <label id="rbb">
          <input type="radio" name="options" value="3" />three</label>
      </section>

js:

function mSessionStorage() {

}

const btn = document.getElementById('submit-btn');

function submit() {
  mSessionStorage();

}

btn.addEventListener('click', submit);