skip to Main Content

i am using laravel with livewire for my website. i am building some kind of wizard containing several steps.

edit: showing whole example
in livewire there is a function called putStepToTwo() that puts $step to 2

<div>
@if($step == 1)

   <h1>First step</h1>
   <button type="button" wire:click="putStepToTwo()">Click Me!</button>

@elseif($step == 2)
   <h1>Second step</h1>

   <script>
       function test(){
           console.log("ok");
       }
       document.addEventListener('step2', function () {
            console.log("ok");
       });
   </script>

   <input onchange="test();" type="range" min="1" max="100" value="50">

@endif
</div>

on page load $step is obv. 1. going through the wizard i will reach step 2 and livewire will trigger the render and my step 2 will be shown (there is no page reload).

unfortunately i cannot use the function test -> going to console and typing test(); results in "is not defined". step 2 will contain sliders that will trigger functions (onchange="test();").

and adding the eventlistener doesnt work either. so dispatching an event from livewire doesnt work.

however if i include the script tag in the blade that is used upon pageload, it works.

now in my imagination the js function test is not "registered" ?!? in javascript. therefore i cannot use it.

can i tell javascript or the dom to search for new functions ?

2

Answers


  1. DOM is Document Object Model, it is related to your HTML code, it cannot detect new functions.

    This happens very often, to fix that you can just put <script> tag into <head> tag, also this will happen if your javascript syntax is wrong.

    Also you can remove the ";" , that may help too:

    <input onchange="test()" type="range" min="1" max="100" value="50">
    

    One more solution is to make javascript define your function and then execute window.test = test before HTML loads (to do this put javascript into head tag)

    And then window.test() should work like test() but correct.

    Sorry if something is wrong, I’m newbie in javascript.

    Login or Signup to reply.
  2. I’ve done some testing and it seems that Livewire does not properly know how to handle HTML tags. Script tags are properly initialized though. What you can do is the following:

    @switch($step)
        @case(1)
            <!-- -->
            @break
        @case(2)
            <input id="test">
    
            <script>
                document.getElementById('test').addEventListener('change', () => {
                    console.log('listener');
                    test();
                });
    
                function test() {
                    console.log('test');
                };
            </script>
            @break
    @endswitch
    

    It is important to define the element before the script, else getElementById is null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search