How to make a variable content format on a page for the user?

Need advice from experienced programmers on how best to organize variable content on a blade template page in Laravel, where data is received.

The task is as follows. Make the ability for users to change the content display format on the page using buttons, card (default), or a table, without re-requesting Ajax on the server.

Thus, data comes from the controller, we sort through it and output it in the card format.

Here are my thoughts:

  1. The simplest thing that comes to mind is to immediately make a blade layout on the page in two formats, cards and tables, and simply hide and display what you need using js. (But it seems to me that this is not very correct, although I may be wrong)
  2. This is to somehow record the data from the controller, maybe in local storage, or something else, and rebuild the layout on request from this data…

Tell me in which direction to go, who has done something similar, maybe they will suggest a more correct or effective option.

I use jq.

JavaScript DOM manipulation in the Browser

I am trying to get an element, and element’s fontSize property and update the size with keypresses. I press the up’ArrowUp’ and down ‘ArrowDown’ but nothing happens, the fontSize property does not change. Could someone please explain to be why the eventListener is not working? Thank you in advance.

let example = document.querySelector('exampleElement')
let exampleSize = getFontSize(example);


function getFontSize(element) {
    return parseInt(window.getComputedStyle(element).fontSize);
}

example.addEventListener('keydown', (event) => {
        switch(event.key){
            case 38:
            example.style.fontSize = `${exampleSize + Math.ceil(exampleSize * .10)}px`;
            break;
            case 40: 
            ballon.style.fontSize = `${exampleSize - Math.ceil(exampleSize * .10)}px`;
            break;
        }
});

I have tried to rewrite this function for well over two hours now, any help would be greatly appreciated! I am expecting the html element to ‘grow’ when the up arrow button on the key board is pressed and the inverse when the down arrow button is pressed.

404 not found error Django URL with JavaScript fetch function

I’m building a Todo app with Django and JavaScript. I’ve reached the point where when I click a “trash” button, the note should be deleted, but it shows an error in the console, the reason for which is not clear to me, since I specified the correct URL path.
The error is appears when I click the “trash” button.

urlpatterns = [
    path('', views.index, name="index"),
    path('add_note/', views.add_note, name="add_note"),
    path('del_note/<int:id>/', views.del_note, name="del_note"),
]

Django view function for deleting a note is also created.

@require_POST
def del_note(request, id):
    del_obj = get_object_or_404(Note, id=id, user=request.user)
    del_obj.delete()

    return JsonResponse({"status": 200, "message": "Note deleted"})

And here is the HTML of the list with that “trash” button.

<ul class="todo__list">
  {% for note in notes %}
  <li class="todo__note flex" data-id="{{ note.id }}">
    <div>
      <input type="checkbox" />
      <span>{{ note.text }}</span>
    </div>
    <div class="delete__edit">
      <button class="edit-btn" id="editBtn" type="button">
        <img src="{% static 'images/edit.svg' %}" alt="" />
      </button>
      <button class="delete-btn" id="deleteBtn" type="button">
        <img src="{% static 'images/delete.svg' %}" alt="" />
      </button>
    </div>
  </li>
  {% endfor %}
</ul>

And this is JS fetch function for send request to django urls “del_note” path.

const noteList = document.querySelector(".todo__list"); 
    //const delUrl = document.body.dataset.delNoteUrl;

    function getCSRFToken() {
      const tokenInput = document.querySelector("input[name='csrfmiddlewaretoken']");
      return tokenInput ? tokenInput.value : "";
    }

    noteList.addEventListener("click", (e) => {
      const deleteBtn = e.target.closest(".delete-btn"); 
      // if (!deleteBtn) return;

      const parentLi = deleteBtn.closest(".todo__note");
      const noteId = parentLi.getAttribute("data-id");

      console.log("Note id:", noteId); // 2 for example

      fetch(`/del_note/${noteId}/`, {
        method: "POST",
        headers: {
          "X-CSRFToken": getCSRFToken(),
        },
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error(`HTTP error ${res.status}`);
          }
          return res.json();
        })
        .then((data) => {
          if (data.status === 200) {
            parentLi.remove();
          } else {
            alert("Fail to delete the note.");
          }
        })
        .catch((err) => {
          console.error("Error:", err);
        });
    });

Error img is here.

enter image description here

Navbar animation flickering only on IOS Device

This is for a Navbar component that only shows up after the user scrolls to a certain section.

At start it should not take up any space in the view.

This works fine as intended.

But observing a flickering issue only when on IOS phone when on a Chrome or Safari browser.

As the navbar appears it flickers. Similar as it disappears, flickers.

Why? Is there a way to fix this?

// Minimized the component just to have a reference.
// Navbar.jsx

const NavBar = () => {
  const showNav = useScrollTrigger(ref);
  return (
    <div>
      <div
        id="id"
        className={classNames(container, showNav && show)}
      >
        <div>There are links, images, buttons in this body</div>
      </div>
    </div>
  );
};

// This is the existing styles.
// NavBar.scss

.container {
  display: flex;
  position: sticky;
  top: 0;
  z-index: 10;
  overflow: hidden;
  // lots of other padding color margin styles

  opacity: 0;
  margin-bottom: -60px;
  visibility: hidden;
  transform: translateY(-100%);
  transition: opacity 0.3s ease, transform 0.3s ease, visibility 0.3s; // have tried removing this, same outcome.
}

.show {
  opacity: 1;
  margin-bottom: 0;
  visibility: visible;
  transform: translateY(0);
}

how do I use JavaScript variables in PHP, or a PHP array with JS? [duplicate]

I only really understand the basics of JavaScript, so I really can’t wrap my head around this problem.

i’m currently using the modal code below to add a new user (data-open). I want to use the same modal to edit the user account using: data-update-id=”. i'm hoping to get the user information from my $employeesarray already inputted into the form ready to edit and update, using Ternary Operators<input id=”first-name” type=”text” name=”firstName” value=”” required />`

$employees is an array from mysql database. print_r =
Array ( [0] => Array ( [id] => 1 [0] => 1 [first_name] => Tracy [1] => Tracy [last_name] => Walker [2] => Walker [password] => [3] => [is_admin] => 0 [4] => 0 ) [1] => Array ( [id] => 2 [0] => 2 [first_name] => Emma [1] => Emma [last_name] => Cooper [2] => Cooper [password] => [3] => [is_admin] => 0 [4] => 0 ) [2] => Array ( [id] => 3 [0] => 3 [first_name] => Savannah [1] => Savannah [last_name] => Gregoire [2] => Gregoire [password] => [3] => [is_admin] => 0 [4] => 0 ) [3] => Array ( [id] => 4 [0] => 4 [first_name] => Helping [1] => Helping [last_name] => Hands [2] => Hands [password] => [3] => [is_admin] => 0 [4] => 0 ) )

const openButton = document.querySelector("[data-open]");
const updateButtons = document.querySelectorAll("[data-update-id]");
const closeButton = document.querySelector("[data-close-modal]");
const modal = document.querySelector("[data-modal]");

updateButtons.forEach(button => {
    button.addEventListener("click", () => {
        // When any of them are clicked, show the modal
        modal.showModal();
    });
});

openButton.addEventListener("click", () => {
    modal.showModal();
});

// close modal
closeButton.addEventListener("click", () => {
    modal.close();
});

modal.addEventListener("click", e => {
    const dialogDimensions = modal.getBoundingClientRect();
    if (
        e.clientX < dialogDimensions.left ||
        e.clientX > dialogDimensions.right ||
        e.clientY < dialogDimensions.top ||
        e.clientY > dialogDimensions.bottom
    ) {
        modal.close();
    }
});
<!--shows a list of the employees-->
<div class="employee-container">
    <div class="employee-button-area">
        <button type="button" class="admin-button" data-open>New Employee</button>
    </div>

    <div class="employee-info-area">
    <?php foreach ($employees as $employee) { ?>
        
        <form class="employee" name="employee" method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
            <span><?= $employee['first_name'] . " " . $employee['last_name']; ?></span>
            <input type="hidden" name="id" value="<?= $employee["id"]; ?>">
            <a style="padding-left: 25px;" data-update-id="<?= $employee["id"]; ?>">Edit</a>
            <input class="delete-button employee-delete-button" type="submit" name="delete" value="Delete" />
        </form>
    <?php }; ?>
    </div>
</div>

<!--modal layout-->
<dialog class="modal" data-modal>
    <form method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]); ?>" class="employee-modal-container" id="new-employee">

        <div class="close-modal-area">
            <span data-close-modal>X</span>
        </div>
        <div class="name-modal-area-1 employee-modal-font">
            <label for="first-name">First name:</label><br>
            <input id="first-name" type="text" name="firstName" value="" required />
        </div>
        <div class="name-modal-area-2 employee-modal-font">
            <label for="last-name">Last name:</label><br>
            <input id="last-name" type="text" name="lastName" value="" required />
        </div>
        <div class="password-modal-area-1 employee-modal-font">
            <label for="password">Password:</label><br>
            <input id="password" type="text" name="password" value="" />
        </div>
        <div class="password-modal-area-2 employee-modal-font">
            <label for="repeat-password">Repeat password:</label><br>
            <input type="text" name="repeatPassword" value="" /></div>
        <div class="is-admin-modal-area employee-modal-font">
            <label>Admin?</label><br>
            <input id="isAdmin" type="radio" name="isAdmin" value="0" required /><label for="is-admin-yes">No</label>
            <input id="isAdmin" type="radio" name="isAdmin" value="1" /><label for="is-admin-no">Yes</label>
        </div>
        <div class="employee-button-model-area">
            <input class="modal-button" type="submit" name="addEmployee" value="Submit" />
        </div>

    </form>
</dialog>

I’ve seen some results on google that showed setting my PHP variables as JS variables, but it all looked very messy for something that is probably quite simple, but I am just missing a piece of the puzzle.

3D Model Compression for Website Integration

I am developing website, and the requirements of client is to add interactive 3D model as well. I am in collaboration with 3D model artist as well. but the problem is that size of that model is too much for website. size of glb is 500 MB, we did apply Draco Compression, and also did some optimization at the very least the size is being reduced to around 50 MB. but it is still too much for websites.

is there any other efficient way to just display the model in interactive way, without consuming too much memory or GPU.

Implementing Lightweight chart custom plugin with konva

I am developing a trading terminal using TradingView’s Lightweight Charts and want to create custom interactive drawing tools.

The Lightweight Chart custom plugin system requires drawing directly on the Canvas API, which makes it difficult to handle mouse events on drawn objects (e.g., detecting clicks or dragging shapes).

On the other hand, Konva.js provides a scene graph and built-in event handling, which would make interactive drawings much easier.

My questions is:

Is it possible to integrate Konva.js on top of Lightweight Charts so that I can use Konva layers for interactive shapes while still using the chart for price/time rendering?

In React ES6, why does the input field lose focus after typing a character unless I add autofocus, but still the whole page reloads?

I have an input field that loses focus and reloads the entire page after every letter added, and when I add an autofocus the page maintains focus but still reloads the page. How do I fix this?

function RestaurantsPage() {
  const [restaurants, setRestaurants] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");

  const filteredRestaurants = restaurants.filter(r =>
    r.name.toLowerCase().includes(searchTerm.toLowerCase())
  );


  useEffect(() => {
    async function fetchRestaurants() {
      setLoading(true);
    
      let query = supabase.from("restaurants").select("id, name");
    
      if (searchTerm.trim() !== "") {
        query = query.ilike("name", `%${searchTerm}%`);
      }
    
      const { data, error } = await query;
    
      console.log("Supabase returned data:", data);
      console.log("Supabase error (if any):", error);
    
      setRestaurants(data || []);
      setLoading(false);
    }
    
  
    fetchRestaurants();
  }, [searchTerm]);

  if (loading) return <p>Loading restaurants...</p>;
  if (error) return <p>Error loading restaurants: {error}</p>;

  return (
    <div>
      <h1>All Restaurants</h1>
      <input
        type="text"
        autoFocus="autoFocus"
        placeholder="Search restaurants"
        value={searchTerm}
        onChange={(e) => {
          setSearchTerm(e.target.value);
          console.log("Search input changed:", e.target.value);
        }}
      />
      <ul>
        {restaurants.map((r) => (
          <li key={r.id}>{r.name}</li>
        ))}
      </ul>
    </div>
  );
}
// 1

I tried adding a key as suggested in other posts but this didnt work.

Adding a list of variables to a spreadsheet

I have a Google Sheet Macro which under certain conditions generates and email with 3 variables in them.
I want it to also place these 3 values on a new line into the same spreadsheet, but on a different tab with the name ‘Action’.

The three values are in a tab called ‘MainCalc’ are as follows:

var name = sourcesheet.getRange(i, 1).getValue();
var action = sourcesheet.getRange(i, 19).getValue();
var percent = sourcesheet.getRange(i, 18).getValue();

So as each condition it’s met I want it to add the results to the next empty line of the speradsheed tab called ‘Action’. So I get something like:

Name Action Percent
Tom Pay 60%
John Reject 89%
Jane Pay 48%

How can I do this with the Google Macro, which I beleive is Javascript?

Many thanks for any help

Disable closing of popup

I have a slightly odd use case for Fancybox 6. I want to open a popup and prevent it from closing.

I can disable the Close button easily enough as an option but I can’t seem to remap the keyboard shortcuts using the keyboard options. Even if I get that to work, users can still click the grey overlay background to close the popup and I’m not sure if I can prevent this.

I can hook into the “on” close event but I cannot prevent the close from happening even if I use return false;:

Fancybox.show([{
  src : "#modal",
  closeButton : false,              
}], {
  on: {
    "close": (fancybox, eventName) => {             
    // Something here to precent closing ...
});

Any ideas?

How to Replace DOCX Placeholder with table in PHPWord?

I’m using the PHPWord package in Laravel to replace placeholders in a DOCX template.

I have a placeholder ${table} in my DOCX file and I’ve done code like:

$tableStyle = [
 'width' => 100 * 50,
 'unit' => 'pct',
 'cellMargin' => 150,
 'borderColor' => '000000',
 'borderSize' => 6,
 ];
 $table = new Table($tableStyle);
 $table->addRow();
 $nameCell = $table->addCell(2000);
 $nameCell->getStyle()->setGridSpan();
 $nameCell->addText('Name', ['bold' => true, 'size' => 8]);
 $processor->setComplexBlock('table', $table);

Now when I add placeholder like:
${table}
${table}

in docx multiple time it’s only replacing first placeholder.

Can anyone tell me what can be issue here? It’s working for the normal placeholder like setValue function for other type of placeholder.

Pdflib PCOS get color space

I’m trying to get the color spaces being used in the file that I am importing using pdflib pcos, and iam getting this error.

“Fatal error: Uncaught PDFlibException: Can’t retrieve object ‘colorspaces[0]/name’ in evaluation mode
(only small documents)…”

Below is my code in php:

   $colorspace_count = $s->pcos_get_number($sraw, "length:colorspaces");
   for ($i = 0; $i <= ($colorspace_count-1); $i++) {
      $color_type[] = $s->pcos_get_string($sraw, "colorspaces[".$i."]/name");
   }
   $color_list = implode(', ',$color_type);

Countdown Timer, struggling with allowing user input and connecting timer with the buttons

I’m an absolute beginner at JavaScript, CSS, and HTML. I’m trying to make a timer, and I’m finding myself struggling to code the JavaScript part. Do you guys have any advice on where to start? I know that there should be a timer with start, stop, and reset buttons, but I also want to let the user edit the actual timer (00:00:00) portion to whatever time they want.

This is all the code I have so far

javascript portion

function startTimer() {

}

css portion

body {
    background-color:lightblue;
}

h1 {
    color: lightcyan;
    text-align: center;
    font-family: monospace;
    font-size: 75px;
}

.down {
    color: lightcyan;
    text-align: center;
    font-family: monospace;
    font-size: 100px;
}

.button-container {
    display: flex;
    justify-content: center; /*centers horizonatally */
    align-items: center; /* centers vertically */
    gap:30px;
    
}
 
.b1 {
    color: white;
    border-color: rgb(180, 219, 255);
    border-radius: 25px;
    padding: 25px;
    background-color: rgb(180, 219, 255);
    font-family: monospace;
    font-size: 50px;
}

.b2 {
    color: white;
    border-color:lightgray;
    border-radius: 25px;
    padding: 25px;
    background-color: lightgray;
    font-family: monospace;
    font-size: 50px;
}

.b3 {
    color: white;
    border-color:lightsteelblue;
    border-radius: 25px;
    padding: 25px;
    background-color: lightsteelblue;
    font-family: monospace;
    font-size: 50px;
}

html portion

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Timer</title>
    <link rel="stylesheet" href="timerStyle.css">
  </head>
  <body>
    <script src="index.js"></script>

    <!--header for timer title-->
    <h1> Timer </h1>

    <!-- div for timer portion!-->
    <div id="count" class="down"> 00:00:00 </div>

    <div class="button-container">
          <button class="b1"> START </button>
          <button class="b2"> RESET </button>
          <button class="b3"> STOP </button>
    </div>

    <script>
      function startTimer() {

      }
    </script>

  </body>
</html>

How to implement security when communicating from Node.js to MongoDB using Mongoose

i have successfully perform CRUD from Node.js to MongoDB using Mongoose.
from node.js file i did a npm install mongoose and npm init -y and name the file index.js

and for package.json i only install mongoose and nodemon

“dependencies”: {
“mongoose”: “^8.16.4”
},
“devDependencies”: {
“nodemon”: “^3.1.10”
}

here is some basic example but my question is how can i implement security within this code

 const mongoose = require('mongoose');

async function connectDB() {
    try {
        await mongoose.connect('mongodb://localhost:27017/myDatabase')
        console.log('MongoDB connected successfully');
    } catch (err) {
        console.error('MongoDB connection error: ', err);
        process.exit(1);
    }
}
connectDB();


const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    age: Number,
})

//User is name of collection
const User = mongoose.model("User", userSchema);

//perform CRUD operations
//create the data or insert data into MongoDb
async function createUser(name, email, age) {
    console.log('create or insert data into MongoDb');
    try {
        const newUser = await User.create({ name, email, age });
        console.log('new user created: ', newUser);
        return newUser;
    } catch (err) {
        console.error('error creating user: ', err);
    }
}


createUser('dude', '[email protected]', 23);


//read retrieve data 2 methods
//method 1
async function getAllUsers() {
    console.log('read or retrieve data');
    try {
        const users = await User.find({});
        console.log("all user: ", users);
        return users;
    } catch (err) {
        console.error('error fetching users: ', err);
    }
}

getAllUsers();


//method 2 retrieve data by id

async function getUserById(id) {
    console.log("retrieve data by ID");
    try {
        const user = await User.findById(id);
        console.log('user found: ', user);
        return user;
    } catch (err) {
        console.error("error finding user by ID:", err);

    }
}

//getUserById('6882e93f9a30b5a80922dd82');


//update data in mongoDb using id

async function updateUser(id, newData) {
    console.log('update data by ID');
    try {
        const updateUser = await User.findByIdAndUpdate(id, newData, { new: true });
        console.log('user updated', updateUser);
        return updateUser;
    } catch (err) {
        console.error('error updating user: ', err);
    }
}


//updateUser('6882e93f9a30b5a80922dd82', { name: "don", age: 22, email: "[email protected]" });


//delete data 
async function deleteUser(id) {
    console.log('delete data by id')
    try {
        const result = await User.findByIdAndDelete(id);
        console.log('user deleted', result);
        return result;
    } catch (err) {
        console.error('error deleting user: ', err);
    }
}

deleteUser('6882e93f9a30b5a80922dd82');