Unique events catered to specific devices: mobile vs. desktop

When a user clicks on the login icon from a desktop, I want a modal dialog to appear. However, when using smaller devices like mobile or tablets, I prefer that a reactjs route is triggered to display in the main content area instead of using a modal dialog.

I am unsure of the best way to achieve this. Initially, I considered having two separate actions for touch and click events, but what if an iPad screen size falls somewhere in between and should show a dialog?

Another option I thought about was having two distinct icons and displaying the appropriate one based on media queries, although I am not fond of duplicating code.

Are there any other approaches I could take? I want to avoid introducing size logic into my JavaScript code since everything else currently relies on media queries.

Answer №1

Utilize a single icon to perform multiple functions.

To determine the browser viewport size, you can implement the matchMedia method in JavaScript, which acts as an equivalent to CSS @media queries. Based on the viewport size, you can dynamically add a specific class to the icon for further actions.

Upon clicking the icon:

  • If it has the .larger-viewport class, a modal dialog will be displayed.
  • If it has the .smaller-viewport class, the reactjs functionality will be triggered.

// Initialize Variables

var iconForModal;
var iconForReact;
var loginIcon = document.getElementsByClassName('login-icon')[0];

// Check and record viewport size

function checkViewportSize() {

    if (window.matchMedia("(max-width: 800px)").matches) {

        loginIcon.className = 'login-icon larger-viewport';
    }

    else {

        loginIcon.className = 'login-icon smaller-viewport';
    }
}

window.addEventListener('resize', checkViewportSize, false);
window.addEventListener('load', checkViewportSize, false);


// Activate Login

function activateLogin() {

    if (loginIcon.classList.contains('larger-viewport')) {

        console.log('Login Modal Activated');

    }

    if (loginIcon.classList.contains('smaller-viewport')) {

        console.log('Login React Activated')
    }
}

loginIcon.addEventListener('click', activateLogin, false);
<button type="button" class="login-icon">Login</button>

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

Refresh the content of VueJS Resource

Resource file helper/json_new.json { "content": { "content_body": "<a href='#' v-on:click.prevent='getLink'>{{ button }}</a>", "content_nav": "", } } Vue script.js file new Vue({ el: 'body', ...

"Implementing a dynamic loading effect in Highcharts triggered by a button

Take a look at this sample highchart fiddle: http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/members/series-setdata/ $('#button').click(function () { var chart = $('#containe ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

How can I arrange a specific array position in Vuejs according to the Id value?

<div v-for="(item, index) in gr" :key="space.id" class="val-name"> </div> After making a few modifications to the API call logic, I was able to achieve my desired outcome. However, the issue lies in the fact that ...

How can I modify the TextField's borderBottom style to be 'none' when it is disabled?

While working within a data cell, I encountered an issue with stacking text. To workaround this obstacle, I opted to create a text field, assign it a value and helper text, disable the field, and change the text color to black when disabled. My current cha ...

A div element with a set width that contains an inline child element

I recently created a basic HTML document with two elements: a div with a fixed width, and an image placed after it. According to my understanding, images are inline elements, so I expected the image to appear next to the div on the right side since there ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Steps for automatically retrying a failed expect statement in Jest

In my React application, I am utilizing Jest for performing unit testing. One aspect of my application involves a Material UI date picker with next and previous buttons. The selected date is displayed in the browser URL. Each time the user clicks on the ne ...

Tips for making a slide-in animation that doesn't require adjusting the browser size

As I work on an animation where an img object and text slide in from outside the frame of the webpage upon page load, everything seems to be running smoothly. But there's one glaring issue: right at the start of the page load, the webpage resizes for ...

"Encountering a problem with using setState in React Hook useEffect

I am currently utilizing the useState hook with two arrays: imageList and videoList. In my useEffect hook, I iterate through the data using forEach method. If the type of the item is an image, it should be pushed to the imageList array. However, after exec ...

Show a single value from the Controller List JSP

Currently, I am displaying multiple values from a controller list of objects to a JSP page. Here is an example of how I am doing it: <tr> <td>Name</td> <td>Email</td> <td>Address</td> ...

In PHP/HTML, input submit does not work with CSS styling

I am struggling with styling the input submit button in my form. I want the button to appear as text with a change in background and font color on hover. Any solutions? input[type="submit"] { font-family: made, mirage; text-decoration: none; backg ...

Issue with Angular *ngFor functionality causing malfunction in Tailwind Elements Select component

Below are my codes for a basic Angular component where I'm utilizing the Tailwind Elemets CSS framework. app.componenets.ts import { Component, OnInit } from '@angular/core'; import { Select, Datepicker, Input, initTE } from "tw-elemen ...

Exploring the Possibilities of Message Embeds in Discord using JavaScript

My goal is to teach my bot how to scan the description of embeds for a specific phrase. After reviewing the documentation at https://discord.js.org/#/docs/main/v11/class/MessageEmbed?scrollTo=description, it appears that I need to implement code similar to ...

Is it possible to replicate keystrokes using Selenium in a CodeMirror text editor?

There are numerous illustrations available that demonstrate how to input text using selenium by utilizing the following code: driver.execute_script('cm.setValue("text")'); While this method works, it does not align with the standard practices o ...

Locate a Sub-Child href Element using Selenium

I am attempting to interact with a link using Selenium automation tool. <div id="RECORD_2" class="search-results-item"> <a hasautosubmit="true" oncontextmenu="javascript:return IsAllowedRightClick(this);" class="smallV110" href="#;cacheurl ...

angular js validation is not working properly

Currently, I am working on a basic HTML page that requires validation using AngularJS. I imported the HTML file with AngularJS in the following manner: <title>Student Registration Form</title> <script src="https://ajax.googleapis.co ...

Prevent random files from being included in RequireJS's r.js optimization process and instead load them asynchronously

Currently, I have successfully implemented RequireJS and a Grunt-based build process that optimizes my JS app into one file using r.js. This consolidation of all app files has proven to be efficient for production deployment. However, the issue arises wit ...

Encountering 404 error when utilizing axios in getInitialProps with Next.js

Why is axios throwing an exception when getInitialProps is called? The service method works fine in other parts of the code. export default function JobIndex({ jobPosts }: JobIndexProps) { return ( <div> <ul> {jobPosts.map(j ...