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!

Showing Posts 1 to 3

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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews