How can Alpine.js and Phoenix 1.7 be properly integrated with LiveView 0.18.3 for initialization?

I'm struggling to make Alpine and Phoenix LiveViews work seamlessly together.

After implementing the code below, I noticed that liveview phx-click events are not triggering, even though Alpine functions properly. Additionally, Tailwind CSS animations do not behave as expected upon page load, but other Tailwind CSS properties style the elements correctly. There is a specific card on the page that should flip over when loaded, but it remains static.

When I remove Alpine.start(), Alpine does not function correctly initially, but starts working after interacting with a liveview component link on the page resembling this:

<.link navigate={~p"/lessons"}>
. All Tailwind CSS, including animations, works perfectly in this scenario. It's worth noting that some parts of Alpine do work upon page load. A particular element with x-show="open" stays hidden due to its parent having
x-data="{ open: false }"
. While the @click="open - !open" successfully alters the value of open, the issue lies in x-show failing to adjust the display: none property as open changes.

If I exclude liveSocket.connect(), Alpine operates correctly at the start, but then the liveviews stop functioning. The card fails to flip and loads overturned instead. It's puzzling how disconnecting the socket affects the CSS.

Moving Alpine.start() just after liveSocket.connect() causes Alpine to malfunction upon page load, while all Tailwind CSS styles and liveview functionalities work properly.

Interestingly (or rather confusingly), eliminating both Alpine.start() and liveSocket.connect() allows Alpine to work flawlessly at page load, but subsequently disables the liveviews.

Researching the functionality of Alpine.start() has proven challenging, and understanding its interaction with liveSocket.connect() is even more perplexing.


Relevant snippet from app.js

import Alpine from '../vendor/alpine'
window.Alpine = Alpine
Alpine.start()

let csrfToken = document.querySelector("meta[name='csrf-token'").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
    params: { _csrf_token: csrfToken },
    hooks: Hooks,
    dom: {
        onBeforeElUpdated(from, to) {
            if (from._x_dataStack) {
                window.Alpine.clone(from, to)
            }
        }
    },
})

// connect if there are any LiveViews on the page
liveSocket.connect()

Relevant piece from nav.ex, an active component

<div class="relative ml-3" x-data="{ open: false }">
  <button
    @click="open = !open"
    @click.outside="open = false"
    type="button"
    class="flex max-w-xs items-center rounded-full bg-white text-sm focus:outline-none focus:ring-2 focus:ring-green focus:ring-offset-2"
    id="user-menu-button"
    aria-expanded="false"
    aria-haspopup="true"
  >
    <span class="sr-only">Open user menu</span>
    <img
      class="h-8 w-8 rounded-full"
      src="https://i.kym-cdn.com/photos/images/facebook/001/431/201/40f.png"
      alt=""
    />
  </button>
  <!--
    Dropdown menu, show/hide based on menu state.
  -->
  <div
    class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
    role="menu"
    aria-orientation="vertical"
    aria-labelledby="user-menu-button"
    tabindex="-1"
    x-show="open"
    x-transition:enter="transition ease-out duration-100"
    x-transition:enter-start="transform opacity-0 scale-95"
    x-transition:enter-end="transform opacity-100 scale-100"
    x-transition:leave="transition ease-in duration-75"
    x-transition:leave-start="transform opacity-100 scale-100"
    x-transition:leave-end="transform opacity-0 scale-95"
    x-cloak
  >...</div>       

Answer №1

The issue stemmed from the rendering context of the live component. It was being rendered outside of a live view, which is against the rules.

To resolve this issue, I converted the live component in nav.ex to a regular Phoenix.Component. Additionally, I removed the lines below from app.js:

window.Alpine = Alpine
Alpine.start()

I made sure to keep the line for importing Alpine:

import Alpine from '../vendor/alpine'

After making these adjustments, I successfully achieved functionality with Alpine, liveview, and CSS loading on page load.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of using em units in web design?

As I delve into an older project that heavily relies on em's for all design elements, including font sizes and layouts, I can't help but question the benefits of using em's in this way. Do they truly offer any advantages when it comes to lay ...

javascript with emphasis on table

My friend shared a JavaScript code with me where he only bolded the time but not the text next to it. I am looking to bold both the time and the text next to it, as well as multiple tables if possible. var hour = new Date().getHours() + 1; $('tabl ...

Display or conceal Badge/Label based on Publication Date surpassing specified amount of days

I stumbled upon this code snippet function check_post_age($days = 5) { $days = (int) $days; $offset = $days*60*60*24; if ( get_post_time() < date('U') - $offset ) return true; return false; } if ( check_post_age(10) ...

What are some solutions for ensuring that the dots on a slideshow function automatically?

My attempt to showcase an automated slideshow seems to be partially successful. The images are changing as intended, but the dots below aren't functioning properly. Although clicking on a dot triggers the desired action, I am aiming for all dots to tu ...

Using Perl script to identify and highlight rows based on specific cell values

I am struggling with how to highlight a row when Column F displays a value of F. I understand that I can achieve this using CSS/JS, but I keep hitting a roadblock. Coding is new to me, so I would greatly appreciate some assistance if possible. Objective: ...

Tips for embedding Jquery code within Vuejs applications

Trying to code a Vue.js Navbar that changes color when scrolling using Jquery and CSS script. It works, but I encountered an error with Vue.js not supporting the syntax '$' after page refresh, resulting in a "$ not defined" error message. As a ne ...

jQuery will not carry out the initial trigger action more than once

I've successfully implemented a feature where clicking on one of the 3 divs causes the main container to slide half away by 600px and reveal a new container with additional options. However, I'm facing an issue where after closing the new content ...

I'm having trouble with my inline list breaking when I try to add something to it. How can I fix this

I'm experiencing an issue where moving my mouse over any of the li's causes them to go out of place. How can I resolve this issue? Here is a demo: https://jsfiddle.net/z970pg6n/ ul { list-style: none; display: block; padding: 0; margi ...

Horizontal expanding and collapsing navigation menu

Is there a way to modify the expand menu bar so it expands from left to right or right to left, instead of top down? Any assistance would be greatly appreciated. Existing Expand Menu Bar <HTML> <HEAD> <META http-equiv="Content-Type" c ...

The tab content refuses to show up in its designated fixed location

I've been working on creating a responsive tab system that functions as an accordion on smaller mobile devices, inspired by this example. I've made great progress and I'm almost where I want to be, but for some reason, the active tab content ...

Mobile device tab animation

I am facing a challenge with a tab containing four items that are vertically stacked on mobile devices. My goal is to animate the clicked li element to move to the bottom of the stack. After experimenting with CSS animations, I was able to achieve this eff ...

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

Ways to eliminate the gap produced by a fixed element

Why is my chatbox (marked in red) creating unnecessary space at the top (highlighted in yellow), even though it has a sticky position and should not be affecting that area? The other elements on the webpage seem to be impacted by this. How can I prevent th ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

Tips for personalizing the FileField in wtforms to function as an image button

I'm attempting to display an image from my project's directory as an icon instead of the standard "choose file" button. Unfortunately, my attempts thus far have been unsuccessful. Not only is the image not loading, but the original button is only ...

Instructions on dynamically positioning a collection of div elements at the center of a webpage container

I am looking to create a set of divs that are centered on the page and adjust in size according to the length of the username. .Container1 { display: table; width: 100%; padding:0; margin:0; -webkit-box-sizing: border-box; -moz-box-sizing: bor ...

Only the cursor CSS is applied to the parent div, not its individual elements within the div

The current issue with the CSS is that it doesn't apply to the cursor setting. It only works if I set cursor:not allowed; to the .bar class and not specific elements like .bar p. My objective is to have all the p elements initially set to not-allowe ...

Retrieve PHP variable from a PHP CSS file

I'm facing an issue where I am unable to retrieve a PHP variable from a CSS file that is loaded in this manner from my index.php: <link href="css/style.php" rel="stylesheet"> Within the style.php file, the code looks like this: <?php heade ...