JS,jQuery,datatables,load img

It seems like you’re encountering issues with handling images in a Laravel + Blade setup while working on a product table in JavaScript. Specifically, you’re having problems with image editing in the modal, where either some images don’t display or, on editing the same recmultiple times, it tries to redirect you or applies changes from the previous record to the next. To address this, you might want to check your image handling logic in the modal edit form and ensure that it properly updates and displays the images for the specific record being edited. Additionally, make sure that you’re handling image references uniquely for each product and not inadvertently affecting other records in the process.

<div class="container">
    @include('shop.modal')
    <div class="card mt-4">
        <div>
            <button class="btn btn-primary" id="addBoxButton">dodaj box</button>
            <button class="btn btn-primary" id="addProductButton">dodaj produkt</button>
        </div>
        <div>
                <div>
                    <div class="col-12" id="tableItem">
                        <table id="boxTable" class="table">
                            <thead>
                            <tr>
                                <th>Purchase Date</th>
                                <th>Cost Price</th>
                                <th>Additional Costs</th>
                                <th>Quantity</th>
                                <th>Action</th>
                            </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                            <table id="productTable" class="table" style="max-width: 200px">
                                <thead>
                                <tr>
                                    <th>name</th>
                                    <th>purchase_date</th>
                                    <th>cost_price_product</th>
                                    <th>additional_costs_product</th>
                                    <th>condition_product</th>
                                    <th>color_product</th>
                                    <th>dictionary_product</th>
                                    <th>new_product</th>
                                    <th>photo</th>
                                    <th>photo_product</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
</div>
</div>
<button type="submit" class="btn btn-primary">Wyślij</button>
        </div>
    </div>
</div>
<script>
    $(document).ready(function () {
        var box = [];
        var boxTables = $('#boxTable').DataTable({
            dom: 'rt',
        });
        var product = [];
        var productTables = $('#productTable').DataTable();
        var photos = [];
        var rowId;
 
        $("#addBoxButton").click(function () {
            $("#modal-add-box").modal("show");
        });
 
        $("#add-box").click(function () {
 
            var newBox = {
                purchase_date_box: $("#purchase_date_box").val(),
                cost_price_box: $("#cost_price_box").val(),
                additional_costs_box: $("#additional_costs_box").val(),
                Quantity_box: $("#Quantity_box").val(),
            };
 
            box.push(newBox);
            boxTables.row.add([
                newBox.purchase_date_box,
                newBox.cost_price_box,
                newBox.additional_costs_box,
                newBox.Quantity_box,
                '<div style="display: flex;"><button class="btn btn-success editBoxButton">Edytuj</button> <button class="btn btn-danger deleteBoxButton">Usuń</button></div>'
            ]).node().setAttribute('data-id', box.length - 1);
            boxTables.draw();
 
            $("#modal-add-box").modal("hide");
 
            $("#purchase_date_box").val("");
            $("#cost_price_box").val("");
            $("#additional_costs_box").val("");
            $("#Quantity_box").val("");
 
        });
 
        $('#boxTable').on('click', '.deleteBoxButton', function () {
            rowId = $(this).closest('tr').data('id');
            boxTables.row($(this).closest('tr')).remove().draw(false);
            box.splice(rowId, 1);
            rowId = null;
        });
 
        $('#boxTable').on('click', '.editBoxButton', function () {
            rowId = $(this).closest('tr').data('id');
var selectedBox = box[rowId];
        $("#purchase_date_box_edit").val(selectedBox.purchase_date_box);
            $("#cost_price_box_edit").val(selectedBox.cost_price_box);
            $("#additional_costs_box_edit").val(selectedBox.additional_costs_box);
            $("#Quantity_box_edit").val(selectedBox.Quantity_box);
$("#modal-edit-box").modal("show");
        });
 
$("#edit-box").click(function () {
            var $this = $(this);
            var editedBox = {
                purchase_date_box: $("#purchase_date_box_edit").val(),
                cost_price_box: $("#cost_price_box_edit").val(),
                additional_costs_box: $("#additional_costs_box_edit").val(),
                Quantity_box: $("#Quantity_box_edit").val(),
            };
 
            box[rowId] = editedBox;
 
            boxTables.row(rowId).data([
                editedBox.purchase_date_box,
                editedBox.cost_price_box,
                editedBox.additional_costs_box,
                editedBox.Quantity_box,
                '<div style="display: flex;"><button class="btn btn-success editBoxButton">Edytuj</button> <button class="btn btn-danger deleteBoxButton">Usuń</button></div>'
]).draw();
 
$("#modal-edit-box").modal("hide");
        });
      $("#addProductButton").click(function () {
$("#modal-add-product").modal("show");
        });
 
$("#add-product").click(function () {
 
var newProduct = {
product_name: $("#name_product").val(),
                product_purchase_date: $("#purchase_date_product").val(),
                product_cost_price: $("#cost_price_product").val(),
                product_additional_costs: $("#additional_costs_product").val(),
                product_condition: $("#condition_product").val(),
                product_color: $("#color_product").val(),
                product_dictionary: $("#dictionary_product").val(),
                product_new: $("#new_product").val(),
                photos: []
            };
 
            const photoContainer = $('#thumbnail-container .thumbnail img');
            const photos = [];
            photoContainer.each(function () {
                const originalSrc = $(this).data('original-src');
                photos.push(originalSrc);
            });
            newProduct.photos = photos; 
            const photoStatus = photos.length > 0 ? "dodane " : "nie dodano";
 
            product.push(newProduct);
            productTables.row.add([
                newProduct.product_name,
                newProduct.product_purchase_date,
                newProduct.product_cost_price,
                newProduct.product_additional_costs,
                newProduct.product_condition,
                newProduct.product_color,
                newProduct.product_dictionary,
                newProduct.product_new,
                newProduct.photos,
                photoStatus,
            '<div style="display: flex;"><button class="btn btn-success editProductButton">Edytuj</button> <button class="btn btn-danger deleteProductButton">Usuń</button></div>'
            ]).node().setAttribute('data-id', product.length - 1);
            productTables.columns([8]).visible(false);
 
            productTables.draw();
 
            $("#modal-add-product").modal("hide");
 
            $("#name_product").val("");
            $("#purchase_date_product").val("");
            $("#cost_price_product").val("");
            $("#additional_costs_product").val("");
            $("#condition_product").val("");
            $("#color_product").val("");
            $("#dictionary_product").val("");
            $("#new_product").val("");
            $('#thumbnail-container .thumbnail').remove();
        });
 
        $('#productTable').on('click', '.deleteProductButton', function () {
            rowId = $(this).closest('tr').data('id');
            productTables.row($(this).closest('tr')).remove().draw(false);
            product.splice(rowId, 1);
            rowId = null;
        });
 
        $('#productTable tbody').on('click', '.editProductButton', function (event) {
            event.preventDefault();
            rowId = $(this).closest('tr').data('id');
 
            var selectedProduct = product[rowId];
            $("#name_product_edit").val(selectedProduct.product_name);
            $("#purchase_date_product_edit").val(selectedProduct.product_purchase_date);
            $("#cost_price_product_edit").val(selectedProduct.product_cost_price);
            $("#additional_costs_product_edit").val(selectedProduct.product_additional_costs);
            $("#condition_product_edit").val(selectedProduct.product_condition);
            $("#color_product_edit").val(selectedProduct.product_color);
            $("#dictionary_product_edit").val(selectedProduct.product_dictionary);
            $("#new_product_edit").val(selectedProduct.product_new);
            photos = selectedProduct.photos;
            $("#modal-edit-product").modal("show");
        });
 
        $("#edit-product").click(function () {
            var $this = $(this);
            var editedProduct = {
                product_name: $("#name_product_edit").val(),
                product_purchase_date: $("#purchase_date_product_edit").val(),
                product_cost_price: $("#cost_price_product_edit").val(),
                product_additional_costs: $("#additional_costs_product_edit").val(),
                product_condition: $("#condition_product_edit").val(),
                product_color: $("#color_product_edit").val(),
                product_dictionary: $("#dictionary_product_edit").val(),
                product_new: $("#new_product_edit").val(),
                photos: []
            };
 
            const photoContainer = $('#thumbnail-container-edit .thumbnail img');
            photoContainer.each(function () {
                const originalSrc = $(this).data('original-src');
                photos.push(originalSrc);
            });
            editedProduct.photos = photos; 
            const photoStatus = photos.length > 0 ? "dodane " : "nie dodano";
            product[rowId] = editedProduct;
 
            productTables.row(rowId).data([
                editedProduct.product_name,
                editedProduct.product_purchase_date,
                editedProduct.product_cost_price,
                editedProduct.product_additional_costs,
                editedProduct.product_condition,
                editedProduct.product_color,
                editedProduct.product_dictionary,
                editedProduct.product_new,
                editedProduct.photos,
                photoStatus,
                '<div style="display: flex;"><button class="btn btn-success editProductButton">Edytuj</button> <button class="btn btn-danger deleteProductButton">Usuń</button></div>'
            ]).node().setAttribute('data-id', product.length - 1);
            productTables.columns([8]).visible(false);
            productTables.draw();
            photos = [];
            $("#modal-edit-product").modal("hide");
 
        });
 
        $('#thumbnail-container-edit').on('click', '.thumbnail img', function () {
            const originalSrc = $(this).data('original-src');
            displayLargeImage(originalSrc);
        });
 
        $('#thumbnail-container-edit').on('click', '.delete-button', function () {
            $(this).parent().remove();
        });
        $('#photo_product_edit').on('change', function () {
            displayThumbnailsEdit(this);
            $(this).val('');
        });
 
            $('#photo_product').on('change', function () {
                displayThumbnails(this);
                $(this).val('');
            });
 
            $('#thumbnail-container').on('click', '.thumbnail img', function () {
                const originalSrc = $(this).data('original-src');
                displayLargeImage(originalSrc);
            });
 
            $('#thumbnail-container').on('click', '.delete-button', function () {
                $(this).parent().remove(); 
            });
            $('body').on('click', '#largeImageModal .btn-secondary', function () {
                $('#largeImageModal').modal('hide');
            });
 
            function displayLargeImage(src) {
                const modalContent = `
        <div class="modal fade" id="largeImageModal" tabindex="-1" role="dialog" aria-labelledby="largeImageModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <img src="${src}" class="img-fluid" alt="Large Image">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Zamknij</button>
                    </div>
                </div>
            </div>
        </div>`;
                $('#largeImageModal').remove();
                $('body').append(modalContent);
                $('#largeImageModal').modal('show');
            }
 
            function displayThumbnails(input) {
                if (input.files && input.files.length > 0) {
                    const thumbnailContainer = $('#thumbnail-container');
                    const maxThumbnailSize = 50;
                    let thumbnailsWrapper = thumbnailContainer.find('.thumbnails-wrapper');
                    if (!thumbnailsWrapper.length) {
                        thumbnailsWrapper = $('<div class="thumbnails-wrapper"></div>');
                    }
 
                    for (let i = 0; i < input.files.length; i++) {
                        const reader = new FileReader();
 
                        reader.onload = function (e) {
                            const img = new Image();
                            img.src = e.target.result;
 
                            img.onload = function () {
                                const canvas = document.createElement('canvas');
                                const ctx = canvas.getContext('2d');
 
                                let width = img.width;
                                let height = img.height;
 
                                if (width > height) {
                                    if (width > maxThumbnailSize) {
                                        height *= maxThumbnailSize / width;
                                        width = maxThumbnailSize;
                                    }
                                } else {
                                    if (height > maxThumbnailSize) {
                                        width *= maxThumbnailSize / height;
                                        height = maxThumbnailSize;
                                    }
                                }
 
                                canvas.width = width;
                                canvas.height = height;
                                ctx.drawImage(img, 0, 0, width, height);
                                const thumbnail = `
                        <div class="thumbnail">
                            <img src="${canvas.toDataURL('image/jpeg')}" data-original-src="${e.target.result}" alt="Thumbnail">
                            <button class="delete-button">X</button>
                        </div>`;
 
                                thumbnailsWrapper.append(thumbnail);
                            };
                        };
 
                        reader.readAsDataURL(input.files[i]);
                    }
                    thumbnailContainer.empty().append(thumbnailsWrapper);
                }
            }
 
        function displayThumbnailsEdit(input) {
            if (input.files && input.files.length > 0) {
                const thumbnailContainer = $('#thumbnail-container-edit');
                const maxThumbnailSize = 50;
                thumbnailContainer.empty();

                for (let i = 0; i < photos.length; i++) {
                    const thumbnail = `
                <div class="thumbnail small-thumbnail">
                    <img src="${photos[i]}" alt="Thumbnail">
                    <button class="delete-button">X</button>
                </div>`;
                    thumbnailContainer.append(thumbnail);
 
                for (let i = 0; i < input.files.length; i++) {
                    const reader = new FileReader();
 
                    reader.onload = function (e) {
                        const img = new Image();
                        img.src = e.target.result;
 
                        img.onload = function () {
                            const canvas = document.createElement('canvas');
                            const ctx = canvas.getContext('2d');
 
                            let width = img.width;
                            let height = img.height;
 
                            if (width > height) {
                                if (width > maxThumbnailSize) {
                                    height *= maxThumbnailSize / width;
                                    width = maxThumbnailSize;
                                }
                            } else {
                                if (height > maxThumbnailSize) {
                                    width *= maxThumbnailSize / height;
                                    height = maxThumbnailSize;
                                }
                            }
 
                            canvas.width = width;
                            canvas.height = height;
                            ctx.drawImage(img, 0, 0, width, height);
                            photos.push(canvas.toDataURL('image/jpeg'));
                            const thumbnail = `
                        <div class="thumbnail">
                            <img src="${canvas.toDataURL('image/jpeg')}" data-original-src="${e.target.result}" alt="Thumbnail">
                            <button class="delete-button">X</button>
                        </div>`;
                            thumbnailContainer.append(thumbnail);
                        };
                    };
 
                    reader.readAsDataURL(input.files[i]);
                }
            }
        }
        $('form').submit(function(event) {
            event.preventDefault();
 
            var boxData = boxTables.rows().data().toArray();
            var productData = productTables.rows().data().toArray();
            var formData = {
                boxData: boxData,
                productData: productData
            };
            $.ajax({
                url: '/shop',
                type: 'POST',
                data: { _token: '{{ csrf_token() }}', formData: formData },
                success: function(response) {
                    console.log('Wysłane')
                    console.log(response.aa);
                },
                error: function(error) {
                    console.log('nie wyslane')
                    // console.error(error);
                }
            });
        });
    });
</script>

And modal

<div class="modal" tabindex="-1" id="modal-add-product">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Dodaj produkt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body after-ajax d-flex flex-column justify-content-center align-items-center">
                    <div class="form-group col-6 text-center mt-1">
                        <label for="name_product"><span class="text-danger">*</span>name:</label>
                        <input type="text" name="name_product" id="name_product" class="form-control" required>
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="purchase_date_product"><span class="text-danger">*</span>purchase_date:</label>
                        <input type="date" name="purchase_date_product" id="purchase_date_product" class="form-control" required>
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="cost_price_product"><span class="text-danger">*</span>cost_price_product:</label>
                        <input type="number" name="cost_price_product" id="cost_price_product" class="form-control" required>
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="additional_costs_product">additional_costs_product:</label>
                        <input type="number" name="additional_costs_product" id="additional_costs_product" class="form-control">
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="condition_product"><span class="text-danger">*</span>condition_product:</label>
                        <select name="condition_product" id="condition_product" class="form-control" required>
                            <option value="1">Excellent</option>
                            <option value="2">Good</option>
                            <option value="3">Fair</option>
                        </select>
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="color_product">color_product:</label>
                        <input type="text" name="color_product" id="color_product" class="form-control">
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="dictionary_product">dictionary_product:</label>
                        <input type="text" name="dictionary_product" id="dictionary_product" class="form-control">
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label class="form-check-label" for="new_product">new_product</label>
                        <input type="checkbox" name="new_product" id="new_product" class="form-check-input">
                    </div>
                    <div class="form-group col-6 text-center mt-2">
                        <label for="photo_product">photo_product:</label>
                        <input type="file" name="photo_product" id="photo_product" class="form-control" multiple accept="image/*">
                    </div>
                    <div id="thumbnail-container"></div>
            </div>
 
            <div class="modal-footer after-ajax">
                <span class="btn btn-secondary" data-bs-dismiss="modal">anuluj</span>
                <span type="submit" id="add-product" class="btn btn-primary">dodaj</span>
            </div>
        </div>
    </div>
</div>
 
 
<div class="modal" tabindex="-1" id="modal-edit-product">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edytuj produkt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body after-ajax d-flex flex-column justify-content-center align-items-center">
                <div class="form-group col-6 text-center mt-1">
                    <label for="name_product_edit"><span class="text-danger">*</span>name:</label>
                    <input type="text" name="name_product_edit" id="name_product_edit" class="form-control" required>
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="purchase_date_product_edit"><span class="text-danger">*</span>purchase_date:</label>
                    <input type="date" name="purchase_date_product_edit" id="purchase_date_product_edit" class="form-control" required>
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="cost_price_product_edit"><span class="text-danger">*</span>cost_price_product:</label>
                    <input type="number" name="cost_price_product_edit" id="cost_price_product_edit" class="form-control" required>
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="additional_costs_product_edit">additional_costs_product:</label>
                    <input type="number" name="additional_costs_product_edit" id="additional_costs_product_edit" class="form-control">
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="condition_product_edit"><span class="text-danger">*</span>condition_product:</label>
                    <select name="condition_product_edit" id="condition_product_edit" class="form-control" required>
                        <option value="1">Excellent</option>
                        <option value="2">Good</option>
                        <option value="3">Fair</option>
                    </select>
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="color_product_edit">color_product:</label>
                    <input type="text" name="color_product_edit" id="color_product_edit" class="form-control">
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="dictionary_product_edit">dictionary_product:</label>
                    <input type="text" name="dictionary_product_edit" id="dictionary_product_edit" class="form-control">
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label class="form-check-label" for="new_product_edit">new_product</label>
                    <input type="checkbox" name="new_product_edit" id="new_product_edit" class="form-check-input">
                </div>
                <div class="form-group col-6 text-center mt-2">
                    <label for="photo_product_edit">photo_product:</label>
                    <input type="file" name="photo_product_edit" id="photo_product_edit" class="form-control" multiple accept="image/*">
                </div>
                <div id="thumbnail-container-edit"></div>
            </div>
 
            <div class="modal-footer after-ajax">
                <span class="btn btn-secondary" data-bs-dismiss="modal">anuluj</span>
                <span id="edit-product" class="btn btn-primary">edytuj</span>
            </div>
        </div>
    </div>
</div>

Certainly, I can help you optimize your code for brevity and efficiency. If you could provide a snippet of the relevant code, especially the parts where you’re experiencing issues or believe it can be improved, I’ll do my best to offer suggestions for simplification and optimization.

Certainly! Please share the specific part of your code that you think is too extensive or where you’re encountering issues. I’ll help you streamline it.

problem with text compression appearing in Devtools [closed]

I’m solving problems with the website’s SEO and this problem appears about text compression. How can I locate and resolve this issue?

I tried looking in the files that appear in the image, but I couldn’t identify the error. The result I expect is that the error disappears and I can compress the text as requested.

I have 2 implementations of writing to a file. Why is the second version so much faster?

Here are the two implementations:

const fs = require('node:fs/promises');
const path = require('path');

(async () => {
    console.time("writeMany");
    const fileHandle = await fs.open(path.join(__dirname, '/data/test.txt'), 'w')

    for(let i = 0; i < 1000000; i++)
    {
        await fileHandle.write(`${i} `);
    }
    console.timeEnd("writeMany");
})(); 

Second version:

const fs = require('node:fs');
const path = require('path');

(async () => {
    console.time("writeMany");
    fs.open(path.join(__dirname, '/data/test.txt'), 'w', (err, fd) => {
        for(let i = 0; i < 1000000; i++)
        {
            fs.writeSync(fd, '${i} `);
        }
    });

    console.timeEnd("writeMany");
})(); 

What is the second version doing that makes it go so much faster? I understand it uses callbacks and so the event loop will process and then execute the callback after the file is opened but I still don’t understand why it’s so much faster? the callback function goes over a million times just like the first implementation before finishing.

How to use map state change event (zooment, moveend) with an html created by folium

I render a map from an html file created by folium by using a python script. As the features of folium are quite restrictive, I have to write javascript code in the python script that will change the folium-based html file to add specific things to my map.

Til now it has worked just by string recognition and overwriting the html file. But now I need to use commands like map.on(‘zoomend’, function() {…}). The problem is that folium uses its own generated map id, e.g. var map_4096f0e4e1cf5363f029e391a7951150 = L.map(“map_4096f0e4e1cf5363f029e391a7951150”,{…}). So I tried the get_name() function provided by folium, and I managed to have a string of the map id created by folium in its html file. But now I am stuck because it is a string version of the map id, so if I try in my python script {map_id}.on(‘zoomend’,function(){…}), it won’t recognized it as the map_id defined within the html file. I can’t just manually change the html file as each time I reload the map page, the map id changes. So I need a dynamic way of retrieving this map id so that I can use it in my python code for “map state change event” -based coding. Or is there a totally other way of doing? (I hope I was clear with my question, the web development world is really new to me).

Js, FIrebase – retrieving items by key

In my application, I am using firebase realtime database, and I require to load a specific amount of documents per 1000ms from a collection in firebase. The first time around, the latest 5 documents should be fetched, and the next run, the 5 latest documents after the previous 5 documents should be fetched.

To try accomplish this I wrote a query like so:

query(child(dbRef, `messages/${chatId`}), orderByKey(), limitToLast(5))

This query orders documents by key (in ascending order) which is fine, however everytime this query runs, it gets the same 5 documents, not the next 5 latest documents. Obviously, this is because there is no indexing available to accomplish this.

I attempted to use startAt and endAt on the date/time the messages were created, however this solution didn’t work as expected and seemed inefficient.

Is there any built in firebase methods to handle this issue, or any other possible solution? Thank you.

How to resolve “Uncaught DOMException” on a third party external JavaScript file?

I have loaded an external Font Awesome JavaScript file on to my page. But for some reason, the Font Awesome icons aren’t displaying on my page. When I looked into the console log for any errors, I noticed the following issue.

The error is:

Uncaught DOMException: Failed to execute ‘setAttribute’ on ‘Element’: ‘rules” is not a valid attribute name.

It’s failing at this line of the code:.

I don’t have control over this code as this is from Font Awesome. Also, I don’t have an element such as "rules" in my HTML so I don’t understand the error message.

I don’t have control over this code as this is from Font Awesome. Also, I don’t have an element such as "rules" in my HTML so I don’t understand the error message. Interestingly, I see this issue only on certain pages, not on all page.

This is how the library is currently loaded to the page:

<script type="text/javascript" src="//kit.fontawesome.com/3ead834.js"></script>

How do I go about resolving this issue?

Mindfusion diagramming on electron.js app – Illegal constructor

Im trying to load a mindfusion diagram on my electron.js app and I am getting the following error. This was working fine when my app was running as a web app, but once i converted my app to a electron.js, only thing did not work was the page with mindfusion diagramming. I investigated alot but could not find the reason for this.

The following is my tsconfig

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "types": ["jest", "vite/client"],
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "noFallthroughCasesInSwitch": true,
    "noEmit": true
  },
  "include": ["src", "custom.d.ts"],
  "declarations": true
}

And my package.json is as follows

{
  "name": "myapp",
  "productName": "myapp",
  "version": "1.0.0",
  "main": ".vite/build/main.js",
  "type": "commonjs",
  "description": "myapp v1",
  "scripts": {
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "publish": "electron-forge publish",
    "lint": "eslint --ext .ts,.tsx ."
  },
  "keywords": [],
  ..............

Im suspecting it has got to do something with how the typescript is converted, but I really have no idea. Can someone explain me the reason for this issue and a possible solution?

enter image description here

Render a div in React with an initial scroll on SSR

I have a mobile SSR Application and React component which is rendering a free scroll horizontal div with images. However I want this div to be rendered such that it’s initially scrolled at the position which displays for example 3rd image in the middle of the screen.

Is there any way to achieve it with SSR on first paint, before hydration, mounting, hooks execution?

Updating html for specific model instance Django

I have a Django template that generates a HTML ‘card-like’ element for each model instance. Each instance (ie ‘post’) have a button, when on click, I would like to update a value within that SAME instance.

I have been able to do this within the database, but am struggling with updating the HTML to match. Currently, my solution is updating ALL instances/posts. However, I only want to update it on the instance that had the button click.

Does this make sense? Let me know if it doesn’t.
I will attach my code below along with an image demonstration. I did try passing through the event ID and making sure they align up for both the button and paragraph tag, but this seemed to not work.

JS:

function signUp(user, event, btn, eventID) {
    var csrftoken = Cookies.get("csrftoken");
    var user_id = user
    var event_id = event

    attendance_count = document.querySelectorAll("#attendance");

    if (btn.classList.contains("event-btn")){
        request_info = "register";
    }
    else if (btn.classList.contains("signUpBtnActive")){
        request_info = "unregister";
    }

    $.ajax({
        type: "POST",
        url: "/event/update-attendance/",
        data: {
            user_id: user_id,
            event_id: event_id,
            request_info: request_info,
            "csrfmiddlewaretoken": csrftoken
        },
    }).done(function(response){
        if (attendance_count){
            attendance_count.forEach(element => {
                event_id = element.getAttribute("event-instance");
                if (event_id == eventID){
                    element.innerHTML = response;
                }
            })
        }
    });

}

My view:

def updateAttendanceView(request):
    if request.method == "POST":
        user_id = request.POST.get("user_id");
        event_id = request.POST.get("event_id");
        request_info = request.POST.get("request_info");
    
        user = User.objects.all().filter(id=user_id)
        event = EventPost.objects.get(id=event_id)

        if request_info == "register":
            #create record in model
            if not EventAttendees.objects.filter(attendee__in=user, event=event).exists():
                event_attendee_record = 
EventAttendees.objects.create_event_attendee(user, event)
                event_attendee_record.save()
                event.attendance += 1
                event.save()

        elif request_info == "unregister":
            #remove record from model
            record = EventAttendees.objects.filter(attendee__in=user, event=event)
            if record:
                record.delete()
                event.attendance -= 1
                event.save()
                print("200 - Request Success - Record removed successfully")
            else:
                print("500 - Request Failed - Record not found")

    html = '<p class="m-0 attendance-font">'+str(event.attendance)+'</p>'
    return HttpResponse(html)

My html template (I have removed the irrelevant stuff)

{% for post in event_posts %}
    <div class="card mb-3 event-card border-0">
        <div class="card-body">
             <div class="container p-2">
                   <div class="row">                            
                        <div class="col-auto pe-3">
                            <div class="row"> 
                                <div class="col p-2">
                                    <div class="d-flex flex-row flex-nowrap align-items-center">
                                        <i class="bi-people pe-1 fs-5"></i>
                                        <p class="m-0 attendance-font" id="attendance" event-instance={{event.id}}>{{post.attendance}}</p>
                                     </div>
                                 </div>
                    
                            <div class="row">
                                <div class="col-auto d-flex">
                                    <button type="button" class="btn shadow-none rounded-pill pt-1 pb-1 event-btn" onclick="signUp('{{user.id}}', '{{post.id}}', this, '{{event_id}}')">Sign Up</button>
                                </div>
                            </div>
                        </div>
                    </div>
               </div>
         </div>
    </div>
{% endfor %}

See the below HTML:
enter image description here

When I click the sign up button on one post (event 6 in this case), the count updates visually for all cards. This is only a frontend issue.

enter image description here

Pause video when not in view swiper.js

I recently started using javascript swiper – https://swiperjs.com. I made the slides to contain html videos. The problem is that if I play a video and then swipe for another slide it (logically) keeps playing in the background and I felt it is a bit annoying. How should I make the videos pause when they’re not in view?

Basic call of the swiper –

// SWIPER SERVICES START
if (document.body.id === "services") {
  const swiper = new Swiper(".swiper", {
    loop: true,
    speed: 600,
    autoplay: {
      delay: 15000,
    },
    // Optional parameters
    direction: "horizontal",
    loop: true,
    // If we need pagination
    pagination: {
      el: ".swiper-pagination",
    },
    // Navigation arrows
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    // And if we need scrollbar
    scrollbar: {
      el: ".swiper-scrollbar",
    },
  });
}
// SWIPER SERVICES END

Slides looking like this

 <div class="swiper-slide">
      <p class="note date">2023</p>
      <p class="note">
        <a
          href="https://video.dk/“
          target="_blank"
          rel="noopener noreferrer"
          ><span>Showreel</span
          ><span
            >&nbsp;<i class="fa-solid fa-arrow-up-right-from-square"></i
          ></span>
        </a>
      </p>
      <video
        src="/img/showreel.mp4"
        preload="metadata"
        controls="controls"
        playsinline
        role="video"
        aria-label=“label”
        aria-describedby="<?php echo $lang['asset_40'] ?>"
        poster="/img/cover"
      ></video>
    </div>

I’m looking forward to read your meaningful non toxic input.
Cheers

Is it possible to use an element’s undefined (auto) height in a variable / calc function?

I’m not having much luck trying to figure this one out (I’m an amateur coder lol)…

Question / Project Details:

I’ve got a two column div. The left column, is a text div with an undefined height (height: auto). The right column, is an image, but the image column’s height needs to be greater than the text column’s height for it to look good.

Is there a way I could set the right column’s height to something like the following?:

/* Let's pretend this left column's height is 463px */
.column.left {
  height: auto;
}

/* And the goal for this right column's height would be 543px */
.column.right {
  height: calc(var(--col-left-height) + 80px);
}

So would it be possible to grab the height of the left column & turn it into a variable without setting a fixed height? I’ve attached an image of the actual layout I’m doing for this project, thank you so much for the help!

Image example of the layout:

enter image description here

Three.js 3d Models suddenly darker and less saturated

I’m currently using three.js to render interactive 3d models for a large project. The code has been released and live on a highly visited website for a handful of months now. Suddenly, without a change to the script, the 3d models are rendering darker, or perhaps, with a lack of hue. The only recently js change within the project, that I am aware of, was an update of all npm packages.

Has anyone experienced a change in how three.js renders 3d .glb files after a package update?

Before altering a script that was working just fine, I wanted to pin point what could have effected a script that remains unchanged. Functionality remains the same, it’s just the hue / saturation that has been altered.

I have attached some examples…

Original rendering example

Current rendering example

Setting variable to null or not? [closed]

For JS (and PHP)…
Should i set an object to null (or unset) after use?

Javascript:

var myHtmlObj = getElementById('myHtmlId');
console.log (myHtmlObj.id);
myHtmlObj = null; /*This line: Yes or not?*/

PHP:

myPHPObj = new myPHPClass;
echo myPHPObj.property;
unset(myPHPObj); /*This line: Yes or not?*/

How can I change my code to solve the problem?

My menu is not working as I want. I usually can write only the menu with for loop, but it doesn’t work like it should. If one item of menu is clicked it remains open until I click it again. The menu which I can write is showing content when I click on it, but the other dropdowns are not closing automatically when I am clicking on another item in menu. How can I change my code to solve the problem and obtain automatic closing of other dropdowns each time I click the next menu item?

const menu = document.getElementsByClassName('menu');
const menucontent = document.getElementsByClassName('item');
const subTitle = document.getElementsByClassName('sub-title');
const subItem = document.getElementsByClassName('sub-item');
for (let i = 0; i < menu.length; i++) {
  menu[i].addEventListener('click', () => {
    menucontent[i].classList.toggle('show');
    menu[i].classList.toggle('darkgrey');
  });

  window.addEventListener('click', function(e) {
    if (!e.target.matches('.menu') && !e.target.matches('.item') && !e.target.matches('.sub-title') && !e.target.matches('.fas')) {
      menu[i].classList.remove('darkgrey');
      menucontent[i].classList.remove('show');
    } else if (e.target.matches('.sub-title') || e.target.matches('.fas')) {
      subItem[0].classList.toggle('present');
      subTitle[0].classList.toggle('clear');
      menu[0].classList.toggle('darkgrey');
      menucontent[0].classList.toggle('show');
    }
  })
}

I was trying to use forEach loop, querySelector and querySelectorAll option but it fails for now.

How do you mock a promise in jest?

This might seem like an obviouos question but its literally not working for me no matter what I do. I set up a Test Component:

export const TestComponent = () => {
  React.useEffect(() => {
    axios.get(`some-url`).then(res => {
      console.log('<---res', res);
    });
  });
  return null;
};

And here is my mock:

jest.mock('axios', () => ({
  get: jest.fn().mockResolvedValue({}),
  // get: jest.fn().mockImplementation(() => Promise.resolve({})),
  // get: jest.fn(() => Promise.resolve({})),
  post: jest.fn(() => Promise.resolve()),
  delete: () => Promise.resolve()
}))

Notice the commented out get calls. I’ve tried all the. different ways I know how to mock out a funcntion but I keep getting the same error no matter what:

TypeError: Cannot read properties of undefined (reading ‘then’)

  124 | export const TestComponent = () => {
  125 |   React.useEffect(() => {
> 126 |     axios.get(`some-url`).then(res => {
      |                          ^
  127 |       console.log('<---res', res);
  128 |     });
  129 |   });

WHat am I doing wrong?