MaxLyman

MaxLyman

I am learning Phoenix and Elixir and making myself a website. I know this is probably not the best way to do what I want but I am up for the challenge. Part of the website is an animation of a bike. There are two main animations that I want to do, the first is just one that goes across the window and stops. The second will follow the user’s scroll and go off the page.

The animation of it going across the screen works:

defmodule MaxLymanWeb.Landing.BikeAnimation do
  use MaxLymanWeb, :live_component

  require Logger

  def mount(socket) do
    {:ok, socket}
  end

  def render(assigns) do
    direction = assigns.direction || "right-to-left"
    animation_number = assigns.animation_number || "1"
    id = "bike-animation-#{animation_number}"

    image = case direction do
      "right-to-left" -> "/images/rtl-road-bike.png"
      "left-to-right" -> "/images/ltr-road-bike.png"
      _ -> {:error, "Invalid direction"}
    end

    padding = case direction do
      "right-to-left" -> "pl-80"
      "left-to-right" -> "pr-80"
      _ -> {:error, "Invalid direction"}
    end

    ride_direction = case direction do
      "right-to-left" -> "scrolling-div-rtl"
      "left-to-right" -> "scrolling-div-ltr"
      _ -> {:error, "Invalid direction"}
    end

    assigns =
      assigns
      |> Map.put(:id, id)
      |> Map.put(:image, image)
      |> Map.put(:padding, padding)
      |> Map.put(:tailwind_class, "#{padding} #{ride_direction}")

    if assigns.scroll do
      render_with_scroll(assigns)
    else
      render_without_scroll(assigns)
    end


  end

  defp render_without_scroll(assigns) do
    Logger.info("Rendering without scroll") # WORKING
    ~H"""
      <div id={@id} class={@tailwind_class}>
        <div name="bike">
          <div class="w-24 h-24">
            <img
              name="bike_img"
              src={@image}
              class={"w-24 h-24"}
              alt="bike"/>
          </div>
        </div>
      </div>
    """
  end

it is the scroll that is giving me the most trouble:


  defp render_with_scroll(assigns) do
    Logger.info("Rendering with scroll")

    ~H"""
     <div>
        <a name="direction" class="invisible"> <%= @direction%></a>
        <a name="id" class="invisible"> <%= @id%></a>
        <div class="overflow-hidden">
          <div id={@id} class={@padding}>
            <div class="w-24 h-24">
              <img
                name="bike_img"
                src={@image}
                class="w-24 h-24"
                alt="bike"/>
            </div>
          </div>
          <script>
            window.addEventListener("scroll", function() {
              var direction = document.getElementsByName("direction")[0].textContent;
              var id = document.getElementsByName("id")[0].textContent;
              var bike = document.getElementById(id);
              var scroll = window.scrollY;
              var translation = direction === "right-to-left" ? scroll/2 : -scroll/2;
              console.log("direction", direction, "bike", id, "scroll", scroll, "translation", translation);
              if (bike !== null) {bike.style.transform = "translateX(" + translation + "px)";}

            });
          </script>
        </div>
     </div>
    """
  end
end

there are no issues in my console and the console.log statement shows that the translation is changing but the bike is still not moving.

The answer could just be this is not what I should be using Phoenix for but I’m too deep now to not give it one more try. If anyone knows a way to make this work I am all ears!

Thanks!

First 3 of 3 Posts Switch mode

sodapopcan

sodapopcan

You’re doing several things wrong here and could be any one or all of them:

  • To get the gotcha out of the way, I think you have stumbled across this.
  • You should be using js hooks as opposed to putting the script tag in heex like that. Hooks ensure the JS fires at appropriate times in the LV lifecycle.
  • Further to the last point, I’m unsure if this is all your code (and I haven’t fully taken in all of what’s there) but if there is anything updating assigns as it scrolls the UI will be updated to whatever the server thinks it should be. This will result in anything JS has done to be overwritten.
  • Always use an appropriate Phoenix function for manipulating assigns (assign, assign_new, update, etc)—they are not merely wrappers around Map.put and are required for change tracking to work.
MaxLyman

MaxLyman OP

Thank you, this is helpful. I am new to Phoenix and haven’t used JS that much either so this will help me get back on track.

MaxLyman

MaxLyman OP

Here is my solution thanks to @sodapopcan for the help:

//app.js
// Hooks
let Hooks = {}
Hooks.BikeAnimation = {
  direction() {return this.el.dataset.direction},
  mounted(){
    // set images based on direction
    var img = this.direction() === "rtl" ? "/images/rtl-road-bike.png" : "/images/ltr-road-bike.png";
    var imageElement = document.getElementById("bike-image");
    imageElement.src = img;

    // set animation based on direction
    window.addEventListener("scroll", e => {
      var scroll = window.scrollY;
      var translation = this.direction() === "rtl" ? -scroll/2: scroll/2;
      var bike = document.getElementById("bike-div");
      if (imageElement !== null ) {
        imageElement.style.transform = `translateX(${translation}px)`;
      }
    });
  }
} 

//bike_animation.ex
  defp render_with_scroll(assigns) do
    Logger.info("Rendering with scroll")
    ~H"""
     <div>
        <div class="overflow-hidden">
          <div id="bike-div" phx-hook="BikeAnimation" data-direction="rtl" class={@padding}>
            <div class="w-24 h-24" >
              <img
                id="bike-image"
                src="/images/rtl-road-bike.png"
                class="w-24 h-24"
                alt="bike"/>
            </div>
          </div>
        </div>
     </div>
    """
  end
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement