How to create “Navbar Search Plugin” like for “AdminLTE v2.4”?

I’m using an old Laravel Application that uses “AdminLTE v2.4“. Then, I want to add “Navbar Search Plugin” (https://adminlte.io/docs/3.1/javascript/navbar-search.html) that you can see on this screenshot: https://imgur.com/a/ghQIFxz.

But I noticed that plugin is only available for “AdminLTE v3”.

So, is there any way to add that “Toggle” Search Form especially in responsive design (that support any screen: tablet and mobile) like “Navbar Search Plugin” is in “AdminLTE v3” in pure JavaScript ?

If so, can you please help me to reproduce the same “Navbar Search Plugin” for my “AdminLTE v2.4” so that it displays correctly on any tablet and mobile ???

Thanks for helping me.

My SWIPER JS simply won’t load/work in Safari?

A website I am writing worked in Chrome, Firefox, Android etc. but failed when I tested on an iPad (Safari), so I narrowed down to the following code to test. Swiper JS is the culprit, at least for me. I added the external JS to see if Safari wasn’t loading the linked files, like a CORS issue I researched, but it is. The external function green() simply changes the background color.

On all my browsers, the swiper works and the background ends up green; on Safari, changes to red (so clearly JS works) and the swiper does not initialize!

Tested on localhost, 10.0.0.26, and even copied over to a domain on Bluehost. Same thing all cases. I already grabbed the latest copy of SwiperJS since I was several behind; does not make a difference.

<html>

<head>
    <link rel="stylesheet" href="swiper.css">
    <script type="application/javascript" src="swiper.js"></script>
    <script type="application/javascript" src="test.js"></script>
    <style>
        .x {
            height: 200px;
            width: 200px;
            background-color: blue;
        }

        .test {
            width: 80%;
        }

    </style>
    <script>
        window.onload = init;

        function init() {

            document.body.style.backgroundColor = 'red';

            var aSwiper = new Swiper('.test', {
                centeredSlides: true,
                effect: 'coverflow',
                slidesPerView: 'auto',
                coverflowEffect: {
                    rotate: 0,
                    slideShadows: false,
                    depth: 200,
                    stretch: 0
                },
                spaceBetween: 25
            });


            green();

        }

    </script>
</head>

<body>
    <div class="swiper test">
        <div class="swiper-wrapper ">
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
            <div class='swiper-slide x'></div>
        </div>
    </div>
</body>

</html>

addition: Using something called ‘Inspect’ was able to start debugging the iPad on my Windows machine, yay, and console comes up with “SyntaxError: Unexpected token ‘…’. Expected a property name.” on line 2456 of swiper.js
Unfortunately this is beyond my current capabilities to reverse-engineer but may help you guys…

Ajax doesn’t execute if condition statements in the controller’s function in codeigniter 4

I’m just beginning to learn jQuery and Ajax along with Codeigniter 4 framework, I have encountered this problem when trying to update some columns in database with Ajax, it happened that Ajax works totally fine and update the data on database through the update function but if condition statement not touched by Ajax through the url, what could a problem?

I expected the Ajax to execute the whole function but it doesn’t

Different behavior when using Puppeteer vs a real web browser (Chrome)

I am trying to scrape data from a website using Puppeteer and it seems that the page is getting redirected in the session opened with Puppeteer and using a web browser normally.

To be able to understand more what’s happening, I am using a headfull browser with the devtools enabled. Once the page gets loaded, I trigger all the user events manually.

If you want to try it this is the code for now :

const browser = await puppeteer.launch({
    headless: false,
    args: [`--window-size=1920,1080`],
    defaultViewport: {
      width:1920,
      height:1080
    },
    devtools: true
  });

  const page = await browser.newPage();

  await page.goto('https://otv.verwalt-berlin.de/ams/TerminBuchen', { waitUntil: 'domcontentloaded' });

Click on “EN” for English, then “Book Appointment”.

In the Network tab, it seems that there is a cancelled request in the Puppeteer version. I am sure this has to do something with this issue.

Any idea on what could be causing this?

Getting all current commands in discord-js

I wanted to make a challenge to make a discord-js bot so I can learn JavaScript, but I faced a challenge when I tried to make a plugin system, and I wanted to just register a command with a function, but I wasn’t able to register multiple commands, this is my exact function:

async registerCommand(commandClassBuilder, client, listener) {
        const rest = new REST({ version: 9 }).setToken(creds.token);
        let tree = [ commandClassBuilder ]
        await rest.put(Routes.applicationGuildCommands(creds.clientId, creds.guildId), { body: tree});
        client.addListener('interactionCreate', (Interaction) => {
            if (!Interaction.isCommand) return;
            if (Interaction.commandName == commandClassBuilder.name) {
                listener(Interaction, client);
            };
        });
        console.log("loaded!")

If anybody can help me, please do, thanks

Blur background of Popup Window

When you click on Forgot your password? Press me a popup window opens. When it opens, I want the background to be blurred. I tried to use filter: blur(20px); but that blurs the window itself which I don’t want.

let forgotField = document.getElementById('field');
let forgot = document.getElementById('forgot');
    forgot.addEventListener('click', () => {
        forgotField.style.display = 'block';
    });
#field {
    display: none;
    position: absolute; 
    top: 80px;
    right:0;
    left:0;
    margin: auto;
    width: 300px;
}
#content {
    background-color: black;
    padding: 40px;
    color: white;
}

#forgot {
    color: black;
}
<body id="login-section">
    <section>
        <a id="forgot">Forgot your password? Press me</a>
    </section>
    
    <div id="field">
        <div id="content">
            <p>Here you can set your password back</p>
        </div>
    </div>
    
</body>

Space Invaders enemies don’t move

I’m trying to make the enemies in Space Invaders move according to the game’s mechanics, but either they don’t move, or they break the 3×3 formation I set up and just move like crazy

class Inimigo {
    constructor(){
        this.Seletores();
        this.enemies = [];
        this.framesPerDirection = 16;
        this.currentFrame = 0;
        this.totalFrames = 35;
        this.enemyWidth = 128;
        this.enemyHeight = 128;
        this.enemyRowCount = 3;
        this.enemyColumnCount = 3;
        this.RenderX = 55
        this.RenderY = 35
        this.enemyX = 0
        this.enemyY = 0
        this.srcX=0;
        this.srcY=0;
        this.movementState = 'andarDireita';
        this.createEnemies()
    }

    Seletores() {
        this.canvas = document.querySelector('canvas');
    } 

    createEnemies() {
        for (let c = 0; c < this.enemyColumnCount; c++) {
            this.enemies[c] = [];
            for (let r = 0; r < this.enemyRowCount; r++) {
                this.enemies[c][r] = { x: 0, y: 0, status: 1,movementState:this.movementState };
            }
        }
        console.log("enemies",this.enemies)
    }

    Animate(frames,sprites){
        const interval = 20;
        const passInterval = frames % interval === 0;
        if (passInterval) {
            this.currentFrame++;
            if (this.currentFrame >= this.framesPerDirection) {
                this.currentFrame = 0;
            }
        }
        this.srcX = (this.currentFrame % this.framesPerDirection) * this.enemyWidth;
        this.Drawing(sprites);
    }

    Play(enemy){
        this.movementState = enemy.movementState
        const canvasWidth = this.canvas.width; // Largura do canvas
        
        // Lógica para mover para a direita
        if (this.movementState === 'andarDireita') {
            this.enemyX += 0.1; // Você pode ajustar a velocidade conforme necessário
            console.log(this.enemyX)
            enemy.x = this.enemyX
        }

        // Lógica para mover para a esquerda quando atingir o final do canvas
        if (this.movementState === 'andarDireita' && enemy.x >= canvasWidth - this.enemyWidth) {
            enemy.movementState = 'andarEsquerda';
        }

        // Lógica para mover para a esquerda
        if (this.movementState === 'andarEsquerda') {
            enemy.x -= 5; // Ajuste a velocidade conforme necessário
        }

        // Lógica para mover para a direita quando atingir a borda esquerda do canvas
        if (this.movementState === 'andarEsquerda' && enemy.x <= 0) {
            enemy.movementState = 'andarDireita';
        }
    }

    Drawing(sprites) {
        sprites.src = './public/Enemies/strip_saucer.png';
        const ctx = this.canvas.getContext('2d');

        for (let columns = 0; columns < this.enemyColumnCount; columns++) {
            for (let rows = 0; rows < this.enemyRowCount; rows++) {
                if (this.enemies[columns][rows].status === 1) {
                    this.enemyX = columns * (this.enemyWidth / 3);
                    this.enemyY = rows * (this.enemyHeight / 5);

                    this.enemies[columns][rows].x = this.enemyX; // Atualize a posição x
                    this.enemies[columns][rows].y = this.enemyY; // Atualize a posição y
                    ctx.beginPath();
                    ctx.drawImage(
                        sprites,
                        this.srcX, this.srcY,
                        this.enemyWidth, this.enemyHeight,
                        this.enemies[columns][rows].x, this.enemies[columns][rows].y + 20,
                        this.RenderX, this.RenderY
                    );
                    ctx.closePath();
                }
            }
        }
    }
    Colision(player,enemy){
        // Lógica para verificar se o inimigo colidiu com o jogador
        const ColidPlayer = player.y + player.height 
        const ColidEnemy = enemy.y + (enemy.height +16)
        if(ColidEnemy>=ColidPlayer){
            return true;
        } else {
            return false;
        }
    }
}
export default Inimigo;

I wanted a way to update this code so they can move according to the game’s proposal (move to the right first,
after hitting the edge of the canvas they will go down 10px and move to the left, after hitting the edge of the canvas they will go down another 10px and move to the right and so on)

I’m using html (with canvas), css and javascript with classes and objects

Reverse text in div by line

I’d like to have the text reversed in a div for each line. So, for instance if the given text is:

apple orange banana
potato salad carrot
abcd efgh ijkl

I’d like to get:

ananab egnaro elppa
torrac dalas otatop
lkji hgfe dcba

Reversing the whole text won’t work as it would flip also the top-down order of the text. So, all I want to achieve is to be able to read the text from right to left.

Is there any easy javascript / jquery solution for this?

style="direction: rtl"

is not a solution, I still need to read from left to right.

Thanks.

CORS ‘ Access-Control-Allow-Origin header’ not found. React front-end/Spring boot Java Backend

I am trying to make a DELETE request using axios on my React front-end. My API is a Java Spring-boot application. My database in run through MongoDB compass. When trying to make a DELETE request, I am getting the following error: CORS Error upon delete request

I have tried to configure Cors on my backend but it seems to not be working:

package dev.xxxx.task;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig  {
    @Value("${allowed.origin}")
    private String allowedOrigin;
    @Bean
    public WebMvcConfigurer getCorsConfig ()
    {
        return new WebMvcConfigurer() 
        {
            @Override
            public void addCorsMappings(CorsRegistry registry)
            {
                registry.addMapping("/**")
                        .allowedOrigins(allowedOrigin)
                        .allowedMethods("*")
                        .exposedHeaders("Access-Control-Allow-Origin"); // Expose the Access-Control-Allow-Origin header
                
            }
        };
    }
}

Front-end request:

const handleDelete = async (stickId)=> 
{
    
    await axios.delete(`http://localhost:8080/api/v1/sticky-note/delete/${stickId}`)
    .then((response) => {alert("Sticky deleted")})

}

I have tried multiple configurations on the backend, however even allowing all of the headers does not work. The front-end delete function is in a class named Sticky-note, which is an object stored in the database. This class is also responsible for rendering the sticky notes.

I have also tried using CrossOrigin(origins =”*”) and other variations of that.

htmx hx-trigger: Don’t work with two triggers

I have an element span for infinite scroll:

{# it is last row of table #}

  {% if paginator.has_next and forloop.last %}
     <span id='triggerElement'
         hx-get="{% url 'api' %}?page={{ paginator.next_page_number }}"
         hx-swap="beforeend"
         hx-target="#loop"
         hx-select=".htmx-scroll"
         hx-trigger="revealed, loadMore">
      </span>
    {% endif %}
  </td>
</tr>
{% endfor %}

and it work fine.

Then, I want to trigger this element manually, with some javascript code:

function triggerUpdate() {
    const elements = document.querySelectorAll('.htmx-scroll');
    const count = elements.length;
    if (count < 3) {
        document.body.dispatchEvent(new Event('loadMore'));
    }
}

And add event loadMore to hx-trigger:

<span id='triggerElement'
      hx-get="{% url 'api' %}?page={{ page.next_page_number }}"
      hx-swap="beforeend"
      hx-target="#loop"
      hx-select=".htmx-scroll"
      hx-trigger="revealed, loadMore from:body">
</span>

And now infinite scrolling not working! When loadMore fire, it perform request and update DOM properly, but nothing happens on revealed event.

Revealed just stop working if I add something dummy as hx-trigger="revealed, abcd">

Look as something wrong with combine revealed with any other event.

How to add “preperation times” to start and end of events in fullCalendar

This code is for a conference room rental service. I have so many problems with time zones and such using FullCalendar that I’m on the brink of just rewriting an entire calendar system from scratch.

I’m using adminlte and free version of fullCalendar v5.10.1 that came with adminlte. My problem is I need to add non clickable (editable:false) events that attach to my events from database. I’m very close achieving that using groupId.
jsFiddle

This is my code simplified (it might fail so added a fiddle similar to this)

var globalevents;
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('calendar');
const calendar = new Calendar(calendarEl, {
  locale: "<%= language %>",
  timeZone:"UTC",
  headerToolbar: {
    left  : 'prev,next today',
    center: 'title',
    right : 'dayGridMonth,timeGridWeek,listMonth'
  },
  views:{
    timeGridWeek:{
        dayHeaderFormat:{
        day: 'numeric',
        weekday: 'long',
      },
    }
  },

  height: '100%',
  allDaySlot: false,
  themeSystem: 'bootstrap',
  events: async function( fetchInfo, successCallback, failureCallback ) {
    let _start = new Date(new Date(parseInt(fetchInfo.start.valueOf())));
    let _end = new Date(new Date(parseInt(fetchInfo.end.valueOf())));
    let d = _start.getDate(),
    m = _start.getMonth()+1,
    y = _start.getFullYear();
    let _d = _end.getDate(),
    _m = _end.getMonth()+1,
    _y = _end.getFullYear();
    
    globalevents= await getEvents("1",y+"-"+m+"-"+d,_y+"-"+_m+"-"+_d);
    addGroup(globalevents);
    successCallback(globalevents);
  },
  initialView:"timeGridWeek",
  snapDuration:'00:10:00',
  slotDuration:'00:30:00',
  slotMinTime:'06:00:00',
  slotMaxTime:'24:00:00',
  eventResizableFromStart:true,
  editable  : true,
  droppable : true, // this allows things to be dropped onto the calendar !!! 
});

function addGroup (infos) {
  infos.forEach(element => {
    let _top  = new Date(element.start).getTime();
    _top-=element.prepTime*1000*60;
    let _bot  = new Date(element.end).getTime();
    _bot+=element.cleanTime*1000*60;
    console.log(element)
    calendar.addEvent({
      title          : 'Prepare',
      start          : new Date(_top),
      end            : new Date(element.start),
      backgroundColor: "#b8622d",
      borderColor: "#b8622d",
      groupId:element.groupId,//"219_order" 
      eventType:"prep",
      display:'block'
      // editable: false,
    });
    calendar.addEvent({
      title          : 'Cleanup',
      start          : new Date(element.end),
      end            : new Date(_bot),
      backgroundColor: "#b8622d",
      borderColor: "#b8622d",
      groupId:element.groupId,//"219_order"
      eventType:"prep",
      display:'block'
      // editable: false,
    });
  });

}
calendar.render();

//JSON from backend

{
  title: "Admin",
  start: "2023-12-29T08:30:00.000Z",
  end: "2023-12-29T15:30:00.000Z",
  backgroundColor: "#00a65a",
  borderColor: "#00a65a",
  allDay: false,
  groupId: id+"_order", //like "219_order"
  cleanTime: 30,
  prepTime: 30,
}

Using this, top and bottom events are sticking to main event but at the same time they are resizable and if “prep” event is resized, it’s main event change size too. And if main event resizes, these maintenance events resize too.
If I make these extra events non editable then they stay in place and stop sticking to main event. I tried deleting all extra events every drag-drop-resize-mounted, recreated them using calendar.getEvents().foreach(…) but it gets very slow, cant have that in production.

Old approach:

// calendar.getEvents().forEach(element => {
//   if(element.extendedProps.eventType == "prep") 
//     element.remove();
//   else {
//     addClean(element);  //smaller version of addGroup function          
//     addPrep(element);  //smaller version of addGroup function
//   }
// });

I put this code in eventDrop, eventResize,viewDidMount and before calendar.render(), but it was slow and did not render in first render. Had to switch views or move one of the events to render extra events.
Tried display:”background” for extra events but then other event gets overlapped on them.

My needs are :

  • top and bottom events should block other events overlapping on them
  • top and bottom events are fixed size in duration, if main event change duration these will stick to start and end.
  • (this may be an other question but:) preperation events should be hidden in month view

If there is a limitation about this (i tried everything in my power) I can work with enlarged events initial time with preperation times, then putting divs inside events and coloring start and end differently. Like event.start += prepTime. Then using eventContent I can add custom styling to events. But it seems too low level intervention that might cause more problems.

How to perform the default logic of a SvelteKit Form Action inside a custom use:enhance SubmitFunction?

I ask the user for confirmation before performing a SvelteKit Form Action. I have a custom submit function which performs the default action logic in case the confirm returns true:

const submit: SubmitFunction = async ({ cancel }) => {
  if (confirm("Are you sure you want to delete this post?")) {
    return async ({ update }) => {
      return update();
    };
  } else {
    cancel();
  }
};

The code above works, but I also tried the following:

const submit: SubmitFunction = async ({ cancel }) => {
  if (confirm("Are you sure you want to delete this post?")) {
    return async ({ result }) => {
      return await applyAction(result);
    };
  } else {
    cancel();
  }
};

And it seems like it does the same thing. Are there any differences between the two snippets in terms of behaviour? Is one recommended over the other for a technical reason?

Html: how to display colored text for a code editor? I tried both with and with a with contenteditable

I’m creating a small live code editor for Html, Css and Javascript. It works fine, but I have a problem coloring the words. For example, I would like the various , “class”, , etc. to each have a different color. Like all code editors, there is a part in which to write code and a part in which to view the preview

I have read many questions on the web and almost all the answers say that you need to use a div with contenteditable, because using <textarea> it is not possible to color the words. But the questions I read showed how to color the code for simple use, but my case is different, because in my case I would have to use that code to display the preview and this causes problems.

I’m having trouble, because my goal is to write the html code and then view the output in a preview (how all live code editors work). This is possible to do with a <textarea>, but if I use a div with contenteditable then there are 2 problems:

enter image description here

FIRST PROBLEM

The first problem is: i won’t be able to write the html code and yours tags, because the various html tags are not displayed in the div with contenteditable (while with enter code here the formatting is correct). I would view this code in editor code:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

But if use div with contenteditable, i view this directly in the editor where i have to write the code:

enter image description here

SECOND PROBLEM

The second problem is: if use div with contenteditable, it will not be possible to view the output in a preview, because the preview recovers the code from the textarea, but cannot recover it from the div with contenteditable, because it cannot read the html tags.

How can I print colored words in a textarea? Is it possible to force the div with contenteditable to display the output in a preview? Or is there some newer better method?

This is my html, css and javascript code using textarea:

index.html

<div class="container--content">
    <div class="content content--active">
        <div class="code-area editor">
          <div class="numbers">
            <span></span>
          </div>
          <textarea id="htmlCode" oninput="showPreview()" wrap="off" onkeyup="updateRowNumbering()">
 <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html> 
          </textarea>
        </div>                   
    </div>
</div>

<div class="preview-area">Preview 
    <iframe id="preview-window"></iframe>
</div>
​

style.css

.code-area {
    display: flex;
    flex-direction: column;
    width: 50%;
    border-right: 1px solid #555;
}
.code-area textarea {
    resize: none;
    outline: none;
    width: 100%;
    font-size: 16px;
}
.preview-area {
    width: 100%;
  height: 100%;
}
.preview-area iframe {
    width: 100%;
    height: 100%;
    border: none;
  background-color: white;
}


.editor {
  display: inline-grid;
  grid-template-columns: 3em auto;
  gap: 10px;
  line-height: 21px;
  border-radius: 2px;
  overflow-y: auto;
  width: 100%;
  height: 240px;
}

.editor>* {
  padding-top: 10px;
  padding-bottom: 10px;
}

.numbers {
  text-align: right;
  background: #333;
  padding-right: 5px;
}

.numbers span {
  counter-increment: linenumber;
}

.numbers span::before {
  content: counter(linenumber);
  display: block;
  color: #888;
}

textarea {
  line-height: 21px;
  border: 0;
  background: transparent;
  color: black;
  min-width: 500px;
  outline: none;
  resize: none;
  padding-right: 10px;
}

code_js.js

//NUMBERS LINES
const textarea = document.querySelector("textarea");
      const numbers = document.querySelector(".numbers");
      textarea.addEventListener("keyup", (e) => {
        const num = e.target.value.split("n").length;
        numbers.innerHTML = Array(num).fill("<span></span>").join("");
        
      });
      textarea.addEventListener("keydown", (event) => {
        if (event.key === "Tab") {
          const start = textarea.selectionStart;
          const end = textarea.selectionEnd;

          textarea.value =
            textarea.value.substring(0, start) +
            "t" +
            textarea.value.substring(end);

          event.preventDefault();
        }
      });


//PREVIEW OUTPUT
function showPreview() {

    var htmlCode = document.getElementById("htmlCode").value;
    
    // var cssCode =
    //  "<style>" + document.getElementById("cssCode").value + "</style>";
    // var jsCode =
    //  "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
    
    var frame = document.getElementById("preview-window").contentWindow.document;
    frame.open();
    //frame.write(htmlCode + cssCode + jsCode);
    frame.write(htmlCode);
    frame.close();
}

color change effect should only trigger on scroll but is already applied when the site loads

I have a video in my HTML that I applied an effect to. It is in color normally and turns black and white on scroll.

I used the script seen here:
(How do I change the color of all images on scroll?) and it does work fine, however when I load the page the video is already black and white and only turns to color when I scroll once. Then the effect works as intended.
There is no other grayscale filter in the CSS that is applied to videos.
I also used this script on an image in a different HTML with the same CSS and have the same problem.
Does anyone know what causes the effect to be applied on load?

The HTML:

var videos = document.getElementsByClassName('normal');
    var changeFrom = 150; 

    window.addEventListener('scroll', function() {
      if (window.scrollY >= changeFrom) {
        [].forEach.call(videos, function(video) {
          video.classList.add('onscroll');
        });
      } else {
        [].forEach.call(videos, function(video) {
          video.classList.remove('onscroll');
        });
      }
    });        



   
 video {
    filter: brightness(0.5);
    display: block;
    width: 100%;
    }

    .normal {
      filter: grayscale(0);
       -webkit-filter:grayscale(0);
    }
    .onscroll {
      filter: grayscale(100%);
       -webkit-filter:grayscale(100%);
    }
    <section  class="titleVideo">
        <div>
            <video class="normal onscroll" src="https://www.pexels.com/video/bartender-making-a-cocktail-3772392/" autoplay muted loop ></video>
        </div>
        </section>

Three.js scripts in HTML markup will not run in final build of React project

I have some three.js scripts in my index.html file, which are displayed on the front page of my website. They appear perfectly fine in my vite dev environment (npx vite), however, when i build the website and preview it (npm run build + npm run preview), the three.js scripts clearly do not run. Here is the console log:console log

To clarify, the two scripts are name.js and ascii.js:
HTML Scripts