communication among native web elements version 1

I am currently working with two nested native web components in the following setup:

<top-nav theme="aqua">
  <nav-link selected>Dashboard</nav-link>
  <nav-link>Settings</nav-link>
  <nav-link>Profile</nav-link>
  <nav-link>Logout</nav-link>
</fancy-tabs>

Each component renders fine on its own, but now I need to establish communication between them.

The simplest use-case is setting a link to be selected.

By default, the dashboard is the selected link.

Now, when I click on the settings link, it should become selected. However, I am unsure of how to notify the dashboard component to remove the selected attribute since only one link can be active at any given time.

My initial thought was to dispatch an event from the clicked element, handle the event in the top-nav element, and then iterate through all children to remove the selected attribute if the element is not the origin of the event.

This approach reminds me of the jQuery era and doesn't feel quite right. Are there any other ideas or suggestions for accomplishing this task?

Answer №1

Here is one solution:

  • First, store a reference to the currently selected element
  • Next, add an event listener for click events at the <top-nav> container level
  • When a click event occurs, examine its target to identify the clicked <nav-link> child
  • Finally, update both the old and new <nav-link> elements as necessary

selected = tn.querySelector('nav-link[selected]')
tn.addEventListener('click', ev => {
  if (selected != ev.target) {
    selected.removeAttribute('selected')
    selected = ev.target
    selected.setAttribute('selected', '')
  }
})
nav-link { cursor: pointer }
nav-link[selected] { background-color: yellow }
<top-nav id="tn" theme="aqua">
  <nav-link selected>Dashboard</nav-link>
  <nav-link>Settings</nav-link>
  <nav-link>Profile</nav-link>
  <nav-link>Logout</nav-link>
</top-nav>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The React button fails to refresh the display

I am working on creating a dynamic input form that, when clicking a button, will generate a new row of description input fields. To keep track of these descriptions, I am using an array within the state: state = { descriptions: [ { ...

Is it possible to make the v-toolbar-title fixed within a v-navigation-drawer using Vuetify?

Can the <v-toolbar-title> be fixed within a <v-navigation-drawer>? <v-card class="d-inline-block elevation-12"> <v-navigation-drawer hide-overlay permanent stateless height="440" value="true"> <v-toolbar color="whi ...

What is the method for graphing data points that include two different y values?

I have been on the lookout for a solution to this question for quite some time now. While there are a few options that come close, I am yet to find the perfect answer. My goal is to create a line chart displaying water levels over time. I would like the d ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Is it feasible to separate the bin and lib dependencies in an npm module?

Imagine you have already successfully released a nodejs module on npm. This module is straightforward - just install and import it, provide a string and a config object, and it will return a string for you. Now, here's the twist: you want this module ...

The schema encountered an error due to the absence of the save method

My current goal is to allow a logged in user to visit any user's URL and follow them. However, I'm encountering an issue: TypeError: Object { _id: 54bd6b90b7d4cc8c10b40cbd, name: 'Johnny', username: 'batman', __v: 0, ...

Unable to access React application on local network from a different computer

Recently, I developed a new react app with create-react-app. However, when I attempted to access the app from another computer on the same network, it appeared to be loading but never actually displayed. Interestingly, I can view all the static files wit ...

Encountering 401 unauthorized error in Laravel Passport, Vue.js, and Axios integration

I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios for making API requests. Below is the script code from my App.vue file: import axios from 'axios'; export default { da ...

Exploring the Logic Behind My State Store Layout - Comparing User Interface to Application State

I'm starting to get a bit confused about the difference between application state and UI state. Whenever a user picks an activity from a list on the page, an API call is triggered to retrieve the announcements for that specific activity. Is the id of ...

Utilizing JQuery's $(document).ready() function following a window.location change

I'm having trouble getting a JavaScript function to run after being redirected to a specific page like "example.com" when the DOM is ready for it to work with. Unfortunately, it seems that $(document).ready() is running before "example.com" finishes l ...

Retrieving form data from within the resource error callback scope

For my client-side validation on submit, I am calling a resource if the form is valid. On success, everything works fine. However, when encountering an error handler, I also perform server-side validation on my data transfer object bean which contains Hibe ...

Getting the Mongoose Model using Express parameters is a simple process

Is it possible to dynamically fetch a mongoose model based on the req.params.model? Check out this example of a Schema const mongoose = require("mongoose"); const Schema = mongoose.Schema; const SmartSchema = new Schema({ SmartPriority: { type: Stri ...

Utilizing Mongoose Schema for CSV Import

My current task involves importing a large CSV file into a mongo DB, where the order of the values will determine the key for each entry in the database: Here is an example of the CSV file structure: 9,1557,358,286,Mutantville,4368,2358026,,M,0,0,0,1,0 9 ...

Can applications on Windows 8 operate using JavaScript, HTML5, and CSS3 that adhere to industry standards?

As a .NET developer, I tuned in to the keynote for the Build Event in Anaheim, California and had some questions regarding the new support for creating Windows 8 applications using JavaScript, HTML5, and CSS3. They showcased several examples and mentioned ...

Combine two elements together and display the outcome in json form

There are two objects that need to be summed up and returned in the same format as the original objects stored in a local file. The first JSON: { "data": [{ "x": "Q1 (J, F, M)", "y": [100, 500, 0], "tooltip": "this is tooltip" }, { "x": "Q2(A, M, ...

CustomTooltips in ChartJS allowing for an enhanced visual presentation of data

I am encountering an issue with my code where I am trying to incorporate images into custom tooltips. The goal is to dynamically generate PNG filenames based on the tooltip name or ID, but I am struggling to find unique values to assign as filenames for ea ...

Getting URL parameters in VueJS after a page redirect has occurred

Currently, I am implementing a Login with Facebook feature in my VueJS application using a Third Party Service (AWS Cognito). The process involves clicking on a "Login with Facebook" button which triggers a redirect to the third party URL where a Sign Up ...

Oops! An error occurred: Uncaught promise rejection - invalid link found for ProductListComponent

I am currently in the process of learning Angular and Ionic, but I am feeling a bit confused as to where my mistake is. I have looked at other questions, but I still can't seem to figure it out. Can anyone provide some assistance? Perhaps someone has ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Can you provide the context of functions within a file in nodejs?

When it comes to functions in files with Node.js, what is their context? To export a function, I typically use one of the following: module.exports = function() {}; or module.someFunction = function () {}; But what happens when a function is declared wit ...