When clicking, display the div; hide when hovering over a different element

My goal is to have a div display on hover, which is currently working fine. However, I also want to add a class when a user clicks on an anchor tag to keep the div visible even after the mouse leaves it. The class should be removed if the user clicks on the anchor tag again or hovers over another div.


    $('#main-menu a').mouseover(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.show().siblings('.widget-container').hide();
    });
    $('#wrap').mouseleave(function() {
        $('.widget-container').hide();
    });
    $('#main-menu a').click(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.addClass('active').siblings('.widget-container').hide();
    });
    $('#wrap').mouseleave(function() {
        $('.widget-container').hide();
    });

To see it in action, click here: Fiddle

Answer №1

Take a look at this: Live Demo

$('#nav-menu a').mouseover(function() {
   var $that = $(this);
   var identifier = $that.attr('ref');
   var $currentElement = $('#' + identifier);
   $currentElement.show().siblings('.element-container').removeClass('selected').hide();
});

Now, for the anchor tag:

$('#nav-menu a').click(function(e) {
   var $that = $(this);
   var identifier = $that.attr('ref');
   var $currentElement = $('#' + identifier);
   $currentElement.toggleClass('selected').siblings('.element-container').removeClass('selected').hide();
   e.preventDefault();
});

Answer №2

Check out the live demonstration here

I would like to make two corrections:

First, please see the code snippet below:

$('#main-menu a').mouseover(function() {
   var $this = $(this);
   var id = $this.attr('rel');
   var $currentWidget = $('#' + id);
    $('.active').removeClass('active');
   $currentWidget.show().siblings('.widget-container').hide();
});

Secondly, here is an updated HTML snippet:

<li><a class="first-link parent" rel="first-widget" href="javascript:">First Link</a></li>

Answer №3

Feel free to give this a shot:

$("#testA").on('click', function() {
    $('#testdv').toggleClass('test');
    $('#testdv').toggle();
});
$(".allOtherdv").hover(
   function() {
      $('#testdv').removeClass('test');
      $('#testdv').hide();
   }
);

<a href="javascript:void(0);" id="testA" >Click Me</a>
<div id="testdv" style="display:none;margin-top:30px;">Destination Div</div>
<div class="alldv">Any other Div</div>

Appreciate it!

Answer №4

For a demonstration of this code in action, please visit the following link: http://jsfiddle.net/Ravindu/b6VF3/

$(document).ready(function() {
$('#main-menu a').mouseover(function() {
    var $this = $(this);
    var id = $this.attr('rel');
    var $currentWidget = $('#' + id);
    $currentWidget.show().siblings('.widget-container').hide();
    if ($('.widget-container').hasClass('active')) {
       $('.widget-container').removeClass('active');
    }
});
$('#main-menu a').click(function() {
   var $this = $(this);
   var id = $this.attr('rel');
   var $currentWidget = $('#' + id);
   $currentWidget.addClass('active').siblings('.widget-container').hide();
});
$('#wrap').mouseleave(function() {
   if ($('.widget-container').hasClass('active')) {

   }else{
       $('.widget-container').hide();
    }
});
});

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

Make changes and delete using ajax

Experience the magic of adding, editing, and deleting items seamlessly using ajax, php, and mysql. Everything flows smoothly until a minor hiccup arises - after adding an item, attempting to edit or delete it requires a page refresh. Allow me to share th ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Establishing connections between check boxes and text entry fields and dynamically updating the data within them

I am attempting to connect a checkbox with a text input so that the value inside the input field can be updated. The issue I'm facing is how to appropriately update the value when the checkbox is checked. For instance, my goal is to display the status ...

The dimensions of the sprites within Three.js geometry

I am interested in creating an animation of sprites moving along a figure, particularly sprites that walk along the figure. An example of what I envision can be seen here: http://armsglobe.chromeexperiments.com/ I found some helpful information related t ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

Is it possible for a navbar in CSS to collapse based on its width?

At the moment, I am utilizing Bootstrap v3.3.6 and jQuery v1.9.1. My current project involves a horizontal navbar that collapses once it reaches a specific screen resolution. I am pleased with how this feature operates and wish to maintain the same breakpo ...

Ways to dynamically adjust the size of a group of images in a limited space without any overflow, scrolling, or the use of media queries?

In my React app, I am receiving a variable number of square images from an API to display. These images come in dimensions of 200px, 512px, or 600px squares and have corresponding jackpot denominations and amounts underneath them with a title above. The di ...

Crafting a lively piece of content within a written passage

My goal is to create a unique dynamic portion of text within a paragraph. I am struggling to develop an in-line div (or span) that can hold elements like an unordered list or multiple spans which can be vertically adjusted to display. Imagine a window with ...

jquery failing to interpret ajax response

After making changes to fix an issue with an ajax request not working in IE, I am now facing a new problem where it is not working in any browser. Surprisingly, the ajax request does receive a proper result, but the result is not being parsed correctly. Ho ...

Grouped Input Layout Bootstrap 4

I am having an issue with Bootstrap regarding how to keep a search bar static on the page. Here is what I have tried so far: https://i.sstatic.net/CqeSF.png Below is the code I am currently using: HTML: <nav class="navbar fixed-top navbar-light bg-l ...

What is the best way to transform the content within a div into accordion tabs exclusively for display on mobile devices?

Looking for a way to make a div and its content into clickable accordion tabs for mobile users. However, the current setup is too wide for desktops and covers too much area on mobile devices. The goal is to allow guests to click on the accordion tab to ex ...

Error: The specified module is missing an export that was requested

Hello, I encountered an error in my console that reads: "Uncaught SyntaxError: The requested module './components/tileHeader/controller.js' does not provide an export named 'tileHeader'". Below is the code snippet causing the issue: co ...

How to Extract Specific Data from JSON Response using Jquery?

How do I extract specific fields from this Json Result or response with the following structure? var WPQ3ListData = { "Row" : [{ "ID": "27", "PermMask": "0x400001f07fff1bff", "FSObjType": "0", "Title": "NOOO", "FileLeafRef": "27_.000", "Total ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Creating a border with a unique and specific image

Is there a way to use an image as the border for my div elements? The key requirement is that the border must be positioned outside the box without affecting its size. It's important to note that all div items have the same width, but varying heights ...

Tips for preventing H1 from taking up the entire div

I'm currently working on developing a new theme for my WordPress website. One issue I've encountered is that the h1 element is causing the top menu to appear below it instead of on the same line. Can anyone help me overcome this challenge? Here& ...

JavaScript truthy values referring to numbers

According to the rules outlined below: Falsy: false 0 (zero) '' or "" (empty string) null undefinded NaN (e.g. the result of 1/0) Truthy: Anything else I'm puzzled as to why, in the tests that follow, only the number 1 is considered "tr ...

Parent whose height is less than that of the child element

I'm working on creating a side menu similar to the one on this website. However, I'm facing an issue with the height of the #parent list element. I want it to match the exact same height as its content (the #child span - check out this jsfiddle). ...

Modifying properties using jQuery

Looking for some assistance here. I currently have a link set up like so: <a id='testOne' onclick="doTest('one'); return false;" title="Test One">One</a> What I'm trying to achieve is for jQuery to perform the followi ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...