Tips for dynamically assigning an Event to an element that adapts to different screen sizes

Scenario: Utilizing a snippet of JQuery to add an event to an element according to its ID. This event slides a menu from the left side of the screen.

Inquiry: As the screen size decreases to <710px, I plan to conceal the original element and reveal a new one (just another icon). However, I aim for this new element to trigger the same event. Should I separately assign the event to both elements or is there a way to combine them into one Event?

Take a look at the example below which showcases my HTML, JS, and CSS. PLEASE KEEP IN MIND THAT THE TRIGGER WILL ONLY FUNCTION IF THE TEST WINDOW WIDTH IS ABOVE 711PX

 window.onload = function(){

   document.getElementById('megga-nav-toggle').addEventListener('click', function () {
       var documentBody = $('#megga-global-menu');
       documentBody.toggleClass('is-active');
       if (documentBody.hasClass('hide-megga')) {
           documentBody.removeClass('hide-megga');
          
           return;
       }
       documentBody.addClass('hide-megga');
       
   });

   document.getElementById("megga-global-menu").addEventListener("mouseleave", menuHide);


  };
   function menuHide() {
       document.getElementById("megga-global-menu").classList.add('hide-megga');
   }
   #megga-global-menu {
       background: red ;
       position: fixed;
       top: 50px;
       bottom: 0;
       left:0px;
       width: 200px;
       z-index: 1000000;
       transition: ease all .6s;
   }
   #megga-global-menu.hide-megga {
       left: -200px;
       transition: ease all .6s;
   }
    #megga-nav-toggle {
       display: inline-block;
       z-index:999998;
       font-size: 30px;
       color: #000;
       cursor: pointer;
   }

@media screen and (min-width: 710px) {
    #megga-navmobile-toggle {
        display:none;
    }
}

@media screen and (max-width: 710px) {
    #megga-nav-toggle {
        display:none;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span id="megga-nav-toggle">FULL SCREEN</span><Bn/><Br/>

<span id="megga-navmobile-toggle">MOBILE SCREEN</span>


<div id="megga-global-menu" class="">
My slide out menu goes here!
</div>

Answer №1

It seems like you are looking to display different icons based on the screen size. One way to achieve this is by using media queries in your CSS to show or hide the icons accordingly.

@media screen and (min-width: 710px) {
  #megga-navmobile-toggle-icon { display: none; }
}
@media screen and (max-width: 710px) {
  #megga-nav-toggle-icon { display: none; }
}

In your HTML, you can structure it like this:

<div id="megga-nav-toggle">
  <span id="megga-nav-toggle-icon">FULL SCREEN</span><br/>
  <span id="megga-navmobile-toggle-icon">MOBILE SCREEN</span>
</div>

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

Looking for a way to ensure a div reaches 100% height within a specified area without exceeding the boundaries of the body?

I am working with jQuery mobile and have specific requirements for my project: The main content will be a large graphic that needs to fill the entire page, with both horizontal and vertical scrolling if necessary. The header should remain fixed at the to ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

Issue with useState in Next.js when fetching data from an API

When attempting to retrieve data from the API, I am receiving a response. However, when trying to set the data to useState using the setAccessData function, the data is not being accessed properly. Despite trying multiple methods, the data continues to sho ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Tips for properly removing Bootstrap 4 tooltips when deleting their corresponding DOM element using html()

In my Bootstrap 4 project, I've implemented a live search box that displays results with tooltips for longer descriptions. I've written jQuery scripts to hide the search results and their parent div when certain events occur, like clearing the se ...

Having trouble initiating MongoDB on localhost with node.js

I'm new to the world of node.js and MongoDB. Trying to set up a simple project has been quite the adventure for me. After navigating to my project directory, I kick things off by typing node init, sticking with the default choices. Following that, I ...

Ways to display a series of images side by side to fill the entire width consistently

I need a solution to display multiple images in a box, all set to the same height and width of 154px x 125px. While this can be achieved, the issue arises when there isn't enough space for the final image, leaving blank areas. Is there a way to make t ...

Getting the Title value from Selenium in Python: A guide

Can someone provide guidance on how to retrieve the title value from this element using Selenium? I have tried the following code but it is returning an empty string. items = driver.find_elements_by_tag_name("li") for item in items: followe ...

Use jQuery to add a class when a specific element is clicked and then remove that class when another element

Currently, I am working on creating a photo frame designer. One of the features I am trying to implement is that when a pattern is clicked, it fills the text with that pattern. I have managed to do this using the .addClass function. However, I have run int ...

An interactive scrollable list on Bootstrap 4.1 with flexible 50% height using the

Looking to design a full-screen layout with a top and bottom half. The top half should display a list of items with a scroll bar if it exceeds half of the screen height. After researching, I found a solution using the following structure: <div id="app ...

If a number already exists, create 3 tables using MySQL and PHP

Currently facing an issue, I am in the process of developing a custom registration form for a browser game. I need to assign planets upon registration to users. Here's the breakdown: 9 galaxies, each galaxy consisting of 400 systems with each syste ...

Exploring Jasmine and AngularJS: Testing a factory function in the context of dependency injection

Looking to create a unit test for a simple factory that calculates the sum of two numbers. (function () { "use strict"; angular .module("math") .factory("addservice", [addTwoNumbers]); function addTwoNumbers(a, b) { ...

What is the correct method for storing or uploading an audio file to a designated destination?

Can anyone help me with storing recorded voices in a specific location and uploading the recorded files to that location? Below is a script for uploading an audio file using upload.php: Reference link: //upload link var upload = document.createElement( ...

The most effective method for creating a native mobile app (for iOS, Android, and more) is by utilizing an existing AngularJS

I developed a cutting-edge AngularJS application utilizing various plugins like angular ui-router, angular-translate, and bootstrap 3. While the app runs smoothly on web browsers of desktops/laptops and smartphones with built-in browsers, I have concerns ...

Is it possible to retrieve a webpage's HTML content using WebClient in C# ASP.NET?

Is it possible to obtain the complete rendered HTML of a webpage using WebClient instead of just the page source? I am attempting to extract data from the HTML of the page. The code I am currently using looks like this: WebClient client = new WebClient( ...

Track the mouse clicks on an image and save them into a database

I'm attempting to track mouse clicks on an image and save all the click locations in a database file. However, I've encountered an issue where I can only retrieve the last click instead of capturing all the clicks during a session. Here's my ...

The minDate function is malfunctioning when used in conjunction with a date picker that includes a time

I am struggling with the date & time picker not working correctly in the following function. I suspect there is a conflict between the minDate function of the jQuery UI time picker. I have tried changing the script location and removing the minDate funct ...

Protractor Error Listings

In order to improve error handling in my Protractor tests, I am exploring how to handle exceptions such as No element found using locator: and provide more informative error messages. viewCompanyDocumentPage.getAttachmentType().then(function (type) { ...

Troubleshooting a JS promise issue with Kriskowal's Q library

I have been working with the kriskowal/q module to create a promise, but I am encountering an issue where it does not enter any function paths - neither the happy path nor the error path. Below is the class where I create the promise: var Q = require(&ap ...

Why does my Node.js server-hosted site get downloaded as a file by IE9, Opera, and older versions of Safari?

I'm feeling completely stuck. This whole situation just doesn't make any sense to me. Even though I'm new to HTML5, CSS, and Javascript, I've put together what I think is a decent (albeit unfinished) website design and a simple (also u ...