Having a Jquery resizing problem? No worries! When the width is less than 768, simply enable the click option. And when the width is

HTML

<div class="profile">
        <a href="#" class="hoverdropdown" onclick="return false;">Profile</a>
                    <ul class="dropdown" style="display: none;">
                      <li><a href="#">Dashboard</a></li>
                      <li><a href="#">Logout</a></li>
                    </ul>
                </div>

Jquery

$(document).ready(function(){
    listDropdown();
});
$(window).resize(function(){
    listDropdown();
});

function listDropdown()
{
    var windowWidth=$(window).width();
    if(windowWidth>=768)
    {
        $(".profile").each(function(){
            $(this).mouseover(function(){
                $(this).find(".dropdown").show();
            });
            $(this).find(".dropdown").mouseout(function(){
                $(this).hide();
            });         
        });
        $(document).mouseout(function(e) { 
            if(($(e.target).parents('.profile').length<=0))
            {
                $(".profile .dropdown").hide();
            }
        });
    }
    else if(windowWidth<769)
    {
        $(".profile").each(function(){
            $(this).click(function(){
                $(this).find(".dropdown").toggle();
                $(this).find(".hoverdropdown").children(".fa-plus").toggleClass("fa-minus");
            });
        });     
    }
}

For window widths less than 768, click option is enabled. For window widths above 768, mouseover option is enabled.

Any alternative solutions are welcome.

View the fiddle here

Answer №1

Give this code a try:


function adjustDropdown() {
    var windowWidth = $(window).width();
    if (windowWidth >= 768) {
        $('.profile').addClass('over');
        $('.profile').removeClass('click');

    } else if (windowWidth < 769) {
         $('.profile').removeClass('over');
        $('.profile').addClass('click');
    }
}
$("body").on('mouseover', '.profile.over', function() {
    $(this).find(".dropdown").show();
});
$(".dropdown").mouseout(function() {
    if ($(this).closest('.profile').is('.over')) {
        $(this).hide();
    }
});

$(document).mouseout(function(e) {
    if ($(e.target).parents('.profile.over').length <= 0) {
        $(".profile.over .dropdown").hide();
    }
});

$("body").on('click', '.profile.click', function() {
    $(this).find(".dropdown").toggle();
    $(this).find(".hoverdropdown").children(".fa-plus").toggleClass("fa-minus");
}); 

Link to the working example

Answer №2

Consider this alternate approach.

HTML

<div class="user-profile">
  <a href="#" class="hover-effect" onclick="return false;">Profile</a>
  <ul class="dropdown-menu">
    <li><a href="#">Dashboard</a></li>
    <li><a href="#">Sign Out</a></li>
  </ul>
</div>

CSS

.dropdown-menu{
  display: none;
}

.hover-effect:hover + ul{
  display: block;
}

// Media query for smaller screens
@media (max-width:767px){
  .open .dropdown-menu{
    display: block;
  }
}

jQuery

$('.hover-effect').click(function(){
  $(this).parent().toggleClass('active')
})

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

Issues with JavaScript Content Loading in epub.js on a Website

Hey there, I'm currently experimenting with the epub.js library and trying to set up the basics. However, I'm encountering an issue where the ebook is not showing up in my browser: <!DOCTYPE html> <html lang="en"> <head&g ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Is it possible to redefine a function that is attached to $ctrl outside of the AngularJS framework?

Within my DOM, there exists an element containing ng-click="$ctrl.goToHome(), which is connected to the logo on my site. This particular element is generated by a third-party AngularJS application. The complete element can be seen below: <img ng-if=":: ...

Changing the background color of required inputs that are empty using jQuery

I need help customizing the background color of required input fields that are left empty when a user submits a form. Some of the fields are optional, but I want only the required ones to be highlighted in red. Specifically, the required fields have been ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Tips for sending parameters to a web service URL through a Phonegap HTML page

In my Phone Gap application, I have an HTML page where I need to pass the values like name, contact, etc. to a Webservice URL. However, I am unsure of where to write the code and how to call the webservice URL. Here is a snippet of my HTML code: <div ...

The onMessage listener in Chrome consistently returns an 'undefined' response

My latest project involves creating a simple chrome extension that utilizes message passing. The goal of the extension is to listen for messages from a specific website (in this case, localhost:8080/*) and respond with a simple "Bye". To test this function ...

Iterate over each key in a JSON object to verify if its corresponding value is blank

I am dealing with a JSON object that has empty values for the keys remarks and address. When extracting the JSON, it displays undefined for these empty values. However, I want to replace the empty values with a - sign instead. I understand that I can achie ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Strange issue with Firefox when utilizing disabled attribute as "disabled"

I found a curious bug in Firefox: Check out (unfortunately not reproducible in jsfiddle) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> < ...

Assign a value to a HubSpot hidden form field by utilizing Javascript

I have a snippet of JavaScript code placed in the head section of my website: <!-- Form ID Setter --> <script> document.querySelector('input[name=form_submission_id]').value = new Date(); </script> My objective is to automat ...

A guide on verifying the percentage value of an element's height in Selenium with Java

I was able to retrieve the element's height in pixels using: element.getCssValue("height") However, the height returned was: Height: 560px What I actually need is for the height to be displayed as: Height: 100% Or perhaps Height: 50% ...

How can I create a CSS animation that fades in text blocks when hovering over an image?

I have been trying to implement CSS3 transitions to create a hover effect where the text and background color fade in when hovering over an image. Despite my attempts with various selectors and transition types, I can't seem to achieve the desired res ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

Speaking about the `this` Vue component in an event listener context

Consider this Vue component that is equipped with a global event listener: let myApp = new Vue({ data: { foo: 0; }, methods: { handle: function(event) { this.foo = 1; // 'this' pertains to the handler, not ...

Condition-based React state counter starts updating

In my current project, I have developed the following React component: import React from "react"; import ReactDOM from "react-dom"; import { WidthProvider, Responsive } from "react-grid-layout"; import _ from "lodash"; const ResponsiveReactGridLayout = Wi ...

Tips for ensuring the vertical scroll bar is always visible on a div element

I need help with maintaining a vertical scroll bar on a div regardless of its height. .myclass { overflow-y: scroll; } <div class="myclass"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the in ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...