crockwave

crockwave

Integrate dropdown menus on app list elements

To integrate dropdown menus in a Phoenix Liveview app, you can use a combination of js, Hooks, CSS and your .leex and .ex code. You can expand on this concept to dynamically adjust your dropdown menu contents, and apply the dropdown in multiple places in your app.

.leex
Create adiv with one or more spans to define your dropdown menu. This example assumes you have multiple items to apply the menu to, you need to assign a unique value to the element, mapped against your app’s state. Apply as many span elements as you need for your menu options. Include a phx-hook reference if you want to listen for click and hover events to close the dropdown

You can customize your dropdown span rendering by examining socket.assigns values in the .leex file.

      <div class="element_container" id="element_container" phx-hook="DropdownContainer">
              <div class = "my_dropdown" phx-click="dropdown" onclick="dropdownOptions('<%= unique_element_id %>')">
                <div id="myDropDown<%= unique_element_id %>" class="dropdown-content">
                  <span phx-click="menu_option_1" phx-value-unique_element_id="<%= unique_element_id %>">Menu Option</span>
                </div>
              </div>
    </div>

Include a script element in your .leex to allow toggling of the dropdown menu on click events.

<script type="text/javascript">
        /* When the user clicks on the button, 
    toggle between hiding and showing the dropdown content */
      function dropdownOptions(player) {
        var b = "playerDropDown"
        var c = b.concat(player)
        document.getElementById(c).classList.toggle("show")
      }
</script>

CSS
Your CSS should include the following for dropdown rendering. The default behavior is display: none; until the show class is detected. The show class is added/removed/toggled by javascript in the .leex and .js files.

.chat_player_dropdown:hover, .chat_player_dropdown:focus {
  background-color: #ddd;
}

.my_dropdown {
  position: relative;
  font-weight: 100;
  font-size: 100%;
  color: #333333;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  left: 24px;
  background-color: #f1f1f1;
  min-width: 55px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
  z-index: 998;
}

.dropdown-content span {
  color: black;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
  text-decoration: none;
  margin-top: 3px;
  line-height: 2.3;
}

.dropdown-content span:hover {
  background-color: #ddd;
}

.show {display: block;}

.js
You can add a Hook to allow the dropdown to disappear on click and hover events on nearby parts of the rendered DOM, to accommodate users that hover or click elsewhere after activating the dropdown

Hooks.DropdownContainer = {
	mounted() {

	    // Close the dropdown if the user clicks outside of it
	    window.onclick = function(event) {
		    if (!event.target.matches('.my_dropdown')) {
		      var dropdowns = document.getElementsByClassName('dropdown-content')
		      var i
		      for (i = 0; i < dropdowns.length; i++) {
		        var openDropdown = dropdowns[i]
		        if (openDropdown.classList.contains('show')) {
		          openDropdown.classList.remove('show')
		        }
		      }
		    }
	    }

		var item = document.getElementById("element_container");
	    item.addEventListener("mouseover", e => {
	       this.pushEvent("restore", {dropdown: "false"})
	    })

		var item = document.getElementById("other_element");
	    item.addEventListener("mouseover", e => {
	       this.pushEvent("restore", {dropdown: "false"})
	    })
	}
}

.ex
If you need to control how you render things while your dropdown is being displayed, you can track it by assigning a dropdown parameter in
socket.assigns, with a default value of “false”.

In some of your event handlers, you would assign dropdown to “false” as a means of allowing normal rendering to commence.

Add a handler as required to detect dropdown activation

  @impl true
  def handle_event("dropdown", _params, socket) do
    {:noreply, assign(socket, dropdown: "true")}
  end

Most Liked

crockwave

crockwave

You assign a unique_element_id to each element that you create with a for statement in your .leex file when you have a common element type, such as a list item. You would normally use a div to contain the unique identifier.

You can see this in action at https://shiptoaster.com, when you host a game, and click on a player or viewer in the left sidebar, where the list is a list of players/viewers, and each can have their own dropdown.

When you create your dropdown span elements in your .leex file, you can use your socket.assigns values to dynamically evaluate one or more of those values so that you can customize how your dropdown span elements are presented. As an example, if you mute a player, you can use that muted state to render a span’ that allows you to unmute that player.

Where Next?

Popular in Guides/Tuts Top

AstonJ
This blog post hit my timeline earlier, and I’ve also been learning about some fantastic Elixir related tips via @pragdave’s new online c...
New
marcelo
I wrote a small article on how to use current_user with coherence on Phoenix. There are already a couple of blogposts about it but I thin...
New
OvermindDL1
Ran across this recently, it’s a set of cheatsheet inforgraphic things of the OTP behaviours on the BEAM: https://github.com/Telichkin/o...
New
f0rest8
Hi, TLDR: form attribute set on the input fields and button submit. I just wanted to share a solution I discovered when making live inl...
New
sergio
Hey there, we’re going to walk through deploying a Phoenix app to a DigitalOcean droplet, manually - no tools no nothing. Just straight u...
New
crockwave
To integrate dropdown menus in a Phoenix Liveview app, you can use a combination of js, Hooks, CSS and your .leex and .ex code. You can...
New
jshprentz
Geoffrey Lessel’s 2019 book, Phoenix in Action, was written for Phoenix 1.4. I found that the book’s code examples did not match the cur...
New
smpallen99
Some advice for Elixir programmers. I was reviewing someone’s Elixir Code yesterday and found a deadlock condition bug in a GenServer im...
New
mhanberg
Hi! I recently finished adding authentication to my Phoenix API, so I wanted to share what I learned. I haven’t created authentication f...
New
dogweather
I just finished a long process of configuring and debugging a Docker Compose-based dev environment. Several late-night hours! I think I’v...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
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
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement