Automatic scroll to element with class

I have a div containing a chapter-list next to a video player. The current playing chapter has the class “.current” added.

<div class="hp_chapter--list">
    <ul class="hp_chapters">
        <li class=""><div><a class="hp_chapter" href="#" data-chapter="0">00:00</a></li>
        <li class=""><div><a class="hp_chapter" href="#" data-chapter="1">00:02</a></li>
        <li class=""><div><a class="hp_chapter" href="#" data-chapter="2">00:03</a></li>
        <li class=""><div><a class="hp_chapter" href="#" data-chapter="3">00:04</a></li>
        <li class=""><div><a class="hp_chapter" href="#" data-chapter="4">00:05</a></li>
        <li class="current"><div><a class="hp_chapter" href="#" data-chapter="5">00:07</a></li>
    </ul>
</div>

There are long videos with a lot of chapters and I have a max height on the “.hp_chapter–list” with an overflow-y: auto. My question is, how can I make the div auto-scrolling so that the current list item is always visible?

I don’t know if the data actually got send to the back to process

So i’m coding a small basic razor page project, and i’m kinda stuck on this part, i don’t know if the CategoryId data actually got send to the back-end for process. I don’t really know much about javascript i ask my friends for a javascript code to send some data to the back-end . Here is the code

Note: the page is UserMainPage.cshtml and UserMainPage.cshtml.cs

Sorry if it a bit mess, this code is for the user to sort out the event using their category.

In UserMainPage.cshtml

<div style="position: relative; margin-left: auto;">
    <select style="height: 40px; border: 1px solid #ddd; border-radius: 4px; padding-left: 10px; font-size: 16px;" id="categorySelect">
        <option value="" hidden>Category</option>
     @if (Model.TblCategory != null && Model.TblCategory.Any())
    {
    foreach (var category in Model.TblCategory)
    {
        <option value="@category.CategoryId">@category.CategoryName</option>
    }
}
else
{
    <option value="0">No categories found</option>
}


    </select>
</div>

Here are the script

<script>
    var categorySelect = document.getElementById('categorySelect');
    categorySelect.addEventListener('change', function () {
        var categoryId = parseInt(categorySelect.value); // convert to integer
        window.location.href = "./UserMainPage?categoryId=" + categoryId;
    });
</script>

In UserMainPage.cshtml.cs

   public async Task<IActionResult> OnPostAsync(int? categoryId, string searchString)
{
    if (categoryId == null && string.IsNullOrEmpty(searchString))
    {
        // If no category is selected and search string is null or empty, return all events
        TblEvent = await _context.TblEvents
            .Include(t => t.Admin)
            .Include(t => t.Category)
            .Include(t => t.Location)
            .ToListAsync();
    }
    else if (categoryId != null)
    {
        // Filter events by category
        TblEvent = await _context.TblEvents
            .Include(t => t.Admin)
            .Include(t => t.Category)
            .Include(t => t.Location)
            .Where(t => t.CategoryId == categoryId)
            .ToListAsync();
    }
    else if (!string.IsNullOrEmpty(searchString))
    {
        // Filter events by search string
        TblEvent = await _context.TblEvents
            .Include(t => t.Admin)
            .Include(t => t.Category)
            .Include(t => t.Location)
            .Where(t => t.EventName.Contains(searchString))
            .ToListAsync();
    }

    return Page();
}

tinymce upload image with custom css

I want to add max-width:’100%’ style to uploaded image. How can I do this?

 file_picker_callback(cb, value, meta) {
                const input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');

                input.onchange = () => {
                    const file = input.files[0];
                    const reader = new FileReader();
                    reader.onload = () => {
                        const id = 'blobid' + new Date().getTime();
                        const blobCache = tinymce.activeEditor.editorUpload.blobCache;
                        const base64 = (<string>reader.result).split(',')[1];
                        const blobInfo = blobCache.create(id, file, base64);
                        blobCache.add(blobInfo);
                        cb(blobInfo.blobUri(), { title: file.name });
                    };
                    reader.readAsDataURL(file);
                };

                input.click();
            },

I use this code to upload image on tinyMce.init.

A bug about curvedifference in JsxGraph

I write code about Venn diagram to draw the specific area with yellow. (Literarlly, we can represent the part as “A∩B-A”)

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>curvedifference Demo</title>
  <script type="text/javascript" src="https://jsxgraph.uni-bayreuth.de/distrib/jsxgraphcore.js"></script>
</head>
<body>
  <div id="jxgbox" style="width:400px;height:400px;"></div>
  <script type="text/javascript">
    var board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-3, 3, 3, -3], axis:true});

    
    var circle1 = board.create('circle', [[-1, 0], 2], {strokeWidth:2, strokeColor:'blue', fillOpacity:0.3});
    var circle2 = board.create('circle', [ [0, Math.sqrt(3)], 2], {strokeWidth:2, strokeColor:'red', fillOpacity:0.3});
    var circle3 = board.create('circle', [[1, 0], 2], {strokeWidth:2, strokeColor:'brown', fillOpacity:0.3});

    let temp = board.create("curveunion", [circle1,circle2],{
        fillColor: "blue",
        fillOpacity: 0
    } )

    board.create("curvedifference", [temp,circle1],{
        fillColor: "yellow",
        fillOpacity: 1
    } )
    board.update();
  </script>
</body>
</html>

Actual output:
enter image description here

Expected output:enter image description here

May I ask is there any solution to fix this bug?

I tried many ways, but it does not help.

Why does my page reloads when I delete or upload something from or to the DOM/API ? I am using the preventDefault(); already

Good day everyone.

So I’m getting my “works” from an API ( http…/api/works ). I have all the works displayed on my main page using fetch method get, but also on a modal that opens up when I click a “modify” button. My modal appears with all the images and a “delete” button on each image so I can delete them from the API/DOM. My problem is that when I click that button :
1: the page reloads ( I do not wish for that to happen )
2: the image is deleted from the main page and the modal and also the API. ( which is what I wish for ).

This is the code I use :

const showModal = document.getElementById("showModal");

showModal.addEventListener("click", async (event) => {
  event.preventDefault();
  // check if user is connected
  const token = localStorage.getItem("token");

  const articles = await fetchData("http://localhost:5678/api/works", {
    headers: { Authorization: `Bearer ${token}` },
  });

  const modalContentImg = document.querySelector(".modalContentBody");
  // Refresh modal body to not have duplicates everytime we open the modal
  modalContentImg.innerHTML = "";

  // Find the first article in the array
  const firstArticle = articles[0];

  articles.forEach((article, index) => {
    const projectArticle = document.createElement("article");
    projectArticle.classList.add("articleWrapper");

    const img = document.createElement("img");
    img.setAttribute("src", article.imageUrl);
    img.setAttribute("data-id", article.id);
    img.classList.add("modalImg");

    const deleteBtn = document.createElement("button");
    deleteBtn.innerHTML = '<i class="fas fa-trash-can"></i>';
    deleteBtn.classList.add("deleteImage");

    const edit = document.createElement("p");
    edit.textContent = "éditer";

    // Add another button only to the first image
    if (article.id === firstArticle.id && index === 0) {
      const moveBtn = document.createElement("button");
      moveBtn.innerHTML = '<i class="fa-solid fa-up-down-left-right"></i>';
      moveBtn.classList.add("moveBtn");
      projectArticle.appendChild(moveBtn);
    }

    // Delete image from API when button is clicked
    deleteBtn.addEventListener("click", async (e) => {
      e.preventDefault();
      const token = localStorage.getItem("token");
      await fetchData(`http://localhost:5678/api/works/${article.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      projectArticle.remove();
      // Delete Image from the main page using the id
      const mainImg = document.querySelector(`[data-id="${article.id}"]`);
      if (mainImg) {
        mainImg.parentNode.remove();
      }
    });

    modalContentImg.appendChild(projectArticle);
    projectArticle.appendChild(img);
    projectArticle.appendChild(deleteBtn);
    projectArticle.appendChild(edit);
  });

  document.getElementById("modal").classList.add("visible");
});

Generate multipe Apache Echarts after another gives initialize problem

I have created a function which generates echarts based on the selection in a dropdown.

switch(graphtype) {
        case "type1": 
            someNameECharts.createChartLineCat({graphData: data, 
                bindTo: "ResultsGraphBatch",
                width: 1000,
                height: 500})                                                        
            break;
        case "type2":
           // myChart.clear();
           // $("#ResultsGraphBatch").empty();
            someNameECharts.createChartLineCat({graphData: data, 
                bindTo: "ResultsGraphBatch",
                width: 1000,
                height: 500})                    
            break;
        etc.

someNameECharts.createChartLineCat refers to a function in a seperate .js file which generates the chart.

This works fine. By default “type1” is generated as expected. When I select “type2” I get this “There is a chart instance already initialized on the dom” Error.

I tried to solve it with a myChart.clear() option but “myChart” is not recognised. Emty the “Div” totally “removes” the div.

This is the function to generate the chart in my seperate .js file:

someNameECharts.createChartLineCat = function(config) {

/// I removed some additional code to keep this short ////

let myChart = echarts.init(document.getElementById(config.bindTo), null, {width: config.width, height: config.height});
let option = {
    title: {
      text: config.title
    },
    toolbox: {
        feature: {
            dataZoom: {},
            saveAsImage: {},
            magicType: {
            type: ['line', 'bar', 'stack']
            }
        }
    },
    color: colorSchema,
    dataset: [
        {
            dimensions: [{name: keyNames[0], type:'ordinal'}, {name: keyNames[1]}, {name: keyNames[2]}],
            source: config.graphData,                
        },              
    ],
    tooltip: {},
    grid: {
      width: '70%',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        },
    xAxis: {
        type: 'category',
        },
    yAxis: {
        type: 'value',
    },
    series: seriesSettings
};

outputDataset.forEach(function(ds) {
  option.dataset.push(ds);
});
    
myChart.setOption(option);
}

SyntaxError: Unexpected token ‘o’, “object(Men”… is not valid JSON

I’ve been working on my first ever project for a customer so it’s very exciting. They are a restaurant and so I wanted them to be able to add dishes to their own menu with an AJAX call.
I just did what I’d been taught at school, which usually worked just fine, except for this time.

There is a problem on line 35/36 where the console.error is. “SyntaxError: Unexpected token ‘o’, “object(Men”… is not valid JSON”

The problem is that I can’t get rid of this error, eventhough I’ve tried different things.

This is my PHP displayMenu file in my Ajax folder

include_once(__DIR__ . "/../bootstrap.php");
if (!empty($_POST)) {

    $dish = new Menu();
    $dish->setTitel($_POST['titel']);   
    $dish->setCategory($_POST['categorie']);
    $dish->setPrijs($_POST['prijs']);
    $dish->setAllergeen($_POST['allergeen']);
    $dish->addMenu();
    var_dump($dish);
   
  
$response = [
    'status' => 'success',
    'message' => 'comment saved'


];
header('Content-type: application/json');
echo json_encode($response);


}

This is my js file

let titel = document.querySelector('#titel').value;
let categorie = document.querySelector('#categorie').value;
let prijs = document.querySelector('#prijs').value;
let allergeen = document.querySelector('#allergeen').value;

let formData = new FormData();

formData.append("titel", titel);
formData.append("categorie", categorie);
formData.append("prijs", prijs);
formData.append("allergeen", allergeen);

//fetch from displayMenu.php in the ajax folder
fetch('ajax/displayMenu.php'
, {

method: "POST",
body: formData

})

.then(response=>response.json())
.then(result=> {


    console.log(result)

})

.catch(error => {
    console.error('Error:', error)


})

e.preventDefault();
})

First of all I did google quite a bit on the problem.
I’ve seen videos where the problem was just the fetch URL. I did try to change that a couple of times by adding or removing some dots.

The result was the same.

Then I tried to look in the headers and network tab. It does result in a .php file instead of a .json object. Payloadpreview + response the connection is correct, the objects to get displayed after being refreshed so the fetch result should be fine. As you can see in the payload, the correct things are being put in the database.

I just don’t know how to get rid of the error.

React MultiSelect dropdown showing inside the popup

Am using react-multi-select-component
when click dropdown, dropdown list going under the div, i need position absolute and proper responsive view.
attached screenshot.

`import MultiSelect from "react-multi-select-component";`
``<MultiSelect
options={options}
value={selectedValue}
onChange={onValueChanged}
label`your text`ledBy="Select"
filterOptions={customSearch}`

enter image description here
/>`
dropdown need position proper

Uploaded jpg from React Native iOS app to Azure Blob Storage will not open but contains base64 data

I’m trying to create a screen on a React Native mobile app that allows a user to upload and crop a profile pic, and then upload to Azure blob storage.

I struggled with this as lots of sites pointed to react-native-fs but when I tried to implement that I always got an error so I gave up.

I can get the file to upload to Azure Blob Storage. If I uploaded a text file it works perfectly and is readable. When I tried to do this with a jpg the file is uploaded but it is not readable. However, if I change the extension to .txt and open it in notepad I can copy the content and paste it into a base64 to image conversion website then it works perfectly.

I feel like I’m so close but can’t make the final hurdle. Here is the code …

  const saveFile = async () => {
    const currentDate = new Date();
    const dateString = currentDate.toUTCString();

    // read the contents of the selectedImage file
    const response = await fetch(selectedImage);
    const fileData = await response.blob();
    const base64Data = await new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(fileData);
      // reader.onload = () => resolve(reader.result.split(",")[1]);
      reader.onload = () =>
        resolve(`data:image/jpeg;base64,${reader.result.split(",")[1]}`);

      reader.onerror = (error) => reject(error);
    });

    var config = {
      method: "put",
      maxBodyLength: Infinity,
      url: "https://clubmanpics.blob.core.windows.net/playerpics/newfile13.jpg",
      headers: {
        "x-ms-version": "2017-11-09",
        "x-ms-date": dateString,
        "x-ms-blob-type": "BlockBlob",
        Authorization: `Bearer ${token}`,
        "Content-Type": "image/jpeg",
        "Content-Length": base64Data.length,
        "Content-Encoding": "base64",
      },
      data: Buffer.from(base64Data, "base64"),
    };

    axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });

I’ve tried the code above with and without the “Content-Encoding”: “base64” string but no luck.

converting a springboot application to an executable exe file

hello colleagues I am new to spring boot
I am trying to convert a web application written in spring boot and front end written in thymeleaf to a desktop application that can then be serve out to users

I was looking at electron js framework but unfortunately I am failing to understand what is going on.
Also tried to create a jar file but the jar file is not executable, my original plan was to use launch4j to then convert the jar in to an exe file but unfortunately that is’nt working

Better way to return a promise that resolves to a stream in Node JS

I’m stuck somehow, I have something like this in my code:

async function download() {

  const source = createReadStreamSomeHow();

  await pipeline(source, fs.createWriteStream("file.ext"));

  return source;
}

I need to return the readable stream (source) and store it in an array somewhere and at the same time pipe the data from the read stream to “file.ext”. But when I call:

let task = await download();
taskArray.add(task);

the pipeline() code pauses execution of the function, hence source is only returned when the data has been completely piped to “file.ext”.

Although I understand why the code behaves this way, I can’t seem to find a way to return the source stream from the download() function and still pipe the data to “file.ext” at the same time. Is there a better way to achieve this and make it work? Thank for the help in advance.