GazeIntoTheAbyss

GazeIntoTheAbyss

I rarely touch JS, but I’ve come into a problem I’m confused about.

I was originally using the below to create a modal for new posts and but I’ve noticed that when I apply JS within the Modal, it stops working if I close and reopen the Modal.

For example I have some JS that will convert text to bold when a button is clicked. This JS works perfectly if I refresh the page or when new_post is first opened. If however I close the modal by either the X or by clicking away, then reopen the modal by either patch or navigate my JS completely stops working. Other handle_events, text entry and form submissions work perfectly, but the JS I’m using to save markdown does nothing. Any button on the modal doesn’t recieve inputs when clicked.

Is there something in the .Modal I’m not aware of that could be causing this conflict? I have no errors in the browser console or VScode terminal to go on. If I remove the Modal and make posts/new it’s own page everything works fine.

I feel like it’s going to come down to things being shown/hidden that are effectively covering my buttons with an invisible layer, but not sure. Totally lost to be honest.

<.modal
  :if={@live_action in [:new_post, :edit]}
  id="post-modal"
  show
  on_cancel={JS.navigate(~p"/user/#{@user.username}/posts")}>

  <.live_component
    module={APP.PostLive.FormComponent}
    id={@post.id || :new}
    title={@page_title}
    action={@live_action}
    current_user={@current_user}
    post={@post}
    patch={~p"/user/#{@user.username}/posts"}
  />
</.modal>

Showing Posts 1 to 5

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Can you show how your JS is implemented? In order for JS to play well with LiveView you need to make sure it’s integrated with a hook.

codeanpeace

codeanpeace

Assuming JS.navigate works like push_navigate, this will shut down the current LiveView and remount a new one, which would wipe away any client side changes made via custom JS.

GazeIntoTheAbyss

GazeIntoTheAbyss OP

So I fixed it by converting it to a hook. Broke my JS, but for test purposes it worked.

How do you know when to use hooks and when not to?

I have some basic JS like this which works if I just leave it floating:

const backButton = document.getElementById('back');

if (backButton !== null) {
  backButton.addEventListener("click", goBack);
}

function goBack() {
  window.history.back();
}

The code that was failing was this but not in a hook. Are there scenarios in which hooks are required and scenarios in which they aren’t, or is it just easier to always use hooks?

const Hooks = {};
    
Hooks.bold = {
  mounted() {

    const textarea = document.getElementById("myTextarea");
    const boldButton = document.getElementById("bold-btn");
    const cursorStart = textarea.selectionStart;
    const cursorEnd = textarea.selectionEnd;
    const text = textarea.value;
    
    boldButton.addEventListener("click", () => {
      if (cursorStart !== cursorEnd) {
        const highlightedText = text.substring(cursorStart, cursorEnd);
        const boldText = `**${highlightedText}**`;
    
        const isBold =
          text.slice(cursorStart - 2, cursorStart) === "**" &&
          text.slice(cursorEnd, cursorEnd + 2) === "**";
    
        if (isBold) {
          // Remove Bold from highlighted text
          const removeBold = `${text.substring(
            0,
            cursorStart - 2
          )}${highlightedText}${text.substring(cursorEnd + 2)}`;
          textarea.value = removeBold;
          // Adjust cursor position
          textarea.selectionStart = cursorStart - 2;
          textarea.selectionEnd = cursorEnd - 2;
        } else {
          // Adds Bold to highlighted text
          const highlightBold = `${text.substring(
            0,
            cursorStart
          )}${boldText}${text.substring(cursorEnd)}`;
          textarea.value = highlightBold;
    
          // Adjust cursor position
          textarea.selectionStart = cursorStart + 2;
          textarea.selectionEnd = cursorEnd + 2;
        }
      }
    
      if (cursorStart === cursorEnd) {
        // Removes Bold if condition is **CURSOR**
        if (
          text.slice(cursorStart - 2, cursorStart) === "**" &&
          text.slice(cursorEnd, cursorEnd + 2) === "**"
        ) {
          const removeBold =
            text.slice(0, cursorStart - 2) +
            text.slice(cursorStart, cursorEnd) +
            text.slice(cursorEnd + 2);
          textarea.value = removeBold;
          textarea.setSelectionRange(cursorStart - 2, cursorEnd - 2);
          // Ends Bold if condition is charCURSOR**
        } else if (
          text.slice(cursorStart - 1, cursorStart) !== "*" &&
          text.slice(cursorEnd, cursorEnd + 2) === "**"
        ) {
          textarea.setSelectionRange(cursorEnd + 2, cursorEnd + 2);
        } else {
          // Adds Bold if condition is CURSOR
          const newBold =
            text.slice(0, cursorStart) + "****" + text.slice(cursorEnd);
          textarea.value = newBold;
          textarea.setSelectionRange(cursorStart + 2, cursorEnd + 2);
        }
      }
    
      // Set focus to textarea
      textarea.focus();
    });
  }
};
GazeIntoTheAbyss

GazeIntoTheAbyss OP

Thanks for the suggestion, it was because I wasn’t using hooks apparently.

codeanpeace

codeanpeace

I suspect what might be happening is that when this is outside the mounted hook, the event listener gets added only once on page load/refresh. So when a live navigation event happens that results in re-mounting e.g. on_cancel={JS.navigate(...)}>, this event listener won’t get re-added to the new button. But by adding this code inside the mounted lifecycle callback of a hook, the event listener will get re-added to the new button upon re-mounting.

Just some speculation, but if your backButton is outside the modal, it won’t get re-mounted and therefore the floating JS addEventListener would work as expected. On the other hand, if your boldButton is within the form live component that gets remounted or modal that gets rendered after initial page load, then floating JS addEventListener would not be sufficient.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
mandar1045
I load tested a plain Phoenix chat app backed by Postgres with 100 million messages in it, everything on default settings, to see what br...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
261 13183 112
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews