GenericJam

GenericJam

Detect page load to get screen size, etc. using hooks

Just posting this for future me and other travelers.

In JS I was used to trying to detect the "load" event as a trigger to do stuff when the page has loaded but that has already fired by the time you would set up a listener so you can just push the event directly inside the mount function (the JS one).

In app.js

const Hooks = {
  ScreenSize: {
    mounted() {
      // If you want to listen on resize and push the same event
      window.addEventListener("resize", (e) => {
        this.pushEvent("page-size", {
          screenWidth: window.innerWidth,
          screenHeight: window.innerHeight,
        });
      });

      this.pushEvent("page-size", {
        screenWidth: window.innerWidth,
        screenHeight: window.innerHeight,
      });
    },
  },
};
// Amended boilerplate...
let csrfToken = document
  .querySelector("meta[name='csrf-token']")
  .getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  hooks: Hooks,
});

Somewhere on the page tie in the event to the named hook. This is in a heex file or a render function. It doesn’t have to be a div.

<div phx-hook="ScreenSize" id="screen-size">

Then in your :live_view module put in a function to handle the event.

def handle_event(
        "page-size",
        %{"screenWidth" => screen_width, "screenHeight" => screen_height},
        socket
      ) do
    # Whatever your logic is ....

    {:noreply, socket}
end

As a side note (not part of the solution). if you really need to listen for a ‘done loading’ event, "phx:page-loading-stop" might work better. I can imagine this potentially being useful on the JS side, not so much the Phoenix side.

I hope this helps!

Most Liked

begedin

begedin

Just to add an option, instead of listening to resize events, you can also setup a ResizeObserver in the hook.

In this case, you get the additional flexibility of choosing whether you want to track the size of the window (rather, html element, or body element), or some specific element, such as the element the hook is attached to.

Where Next?

Popular in Questions Top

qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement