Combining hover and mousedown event listeners in jQuery: Tips and tricks

htmlCODE:

<div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0">
    <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; height:40px; z-index: -2"></div>
</div>

$('.original_circle').mousedown(function() {
  $(this).find('div.another_circle').css('left', '50%');

  $('.another_circle').hover(function() {
    console.log('hover mouse in')
  }, function() {
    console.log('hover mouse out')
  });
});

$(document).mouseup(function() {
  console.log('mouse up')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0">
  <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; height:40px; z-index: -2"></div>
</div>

This sample of code displays two circles. Upon clicking on the .original_circle element, another circle (with the class another_circle) appears from a different position. While the mouse is being held down, if it hovers over the another_circle, the following events should occur:

$('.another_circle').hover(function(){
    console.log('hover mouse in')
    }, function(){
    console.log('hover mouse out')
});

These actions are intended to be executed according to the code above.

However, there seems to be an issue with its functionality.

How can this feature be implemented correctly?

EDIT : add codepen

link : https://codepen.io/anon/pen/gvYvWg

In the provided codepen example, I aim to change the color of another_circle to either red or orange.

Answer №1

The issue lies in the z-position of another_circle, as that div is positioned behind original_circle, specifically moving -2 units lower than it.

To resolve this, consider adjusting the z-index attribute to a higher value, such as z-index = 999.

Additionally, it is recommended by JQuery best practices to store every selector execution in a variable for better performance, like so:

var $anotherCircle = $(this).find('div.another_circle');
.

Execute this code snippet:

$('.original_circle').mousedown(function() {
  var $anotherCircle = $(this).find('div.another_circle');
  $anotherCircle.css({
    'left': '50%',
    'z-index': 999
  }).hover(function() {
    console.log('hover mouse in')
  }, function() {
    console.log('hover mouse out')
  });
});

$(document).mouseup(function() {
  console.log('mouse up')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0">

  <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; height:40px; z-index: -2">

  </div>
</div>

As you can see, the mouseenter and mouseout functions are now being properly executed.

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

When working with Bootstrap-Vue, what is the best way to stop a b-dropdown from closing when a nested b-input component is clicked on?

I'm struggling to grasp the concept of Vue's Event Modifiers. The documentation suggests that adding this simple code should do the trick: <!-- the click event's propagation will be stopped --> <a v-on:click.stop="doThis"& ...

Converting nested JSON to CSV for simplified data organization

I need help flattening JSON in order to parse it as a CSV. The current flattening process is not working correctly, as the customer.addresses field is being filled with 'addresstype: r' and then skipping all other fields such as city, countrycode ...

navigating between html pages using sliding next and previous buttons

I am in the process of developing a multi-page form spread across 4 different pages. I would like to incorporate next and previous buttons to allow users to easily navigate through the form. Although I have tried looking online for solutions, most results ...

Having problems with OS X causing issues with my CSS, any solutions to resolve this?

After creating a form and styling it with CSS, I noticed that the form appears differently on my Mac than on Windows. The elements are smaller and the colors have changed. Why is OS X affecting my CSS? Is there a solution to this issue? Here is an image s ...

Assemblage of Marionettes: Adding multiple elements to the DOM

I am working on a Marionette application and have come across an issue with inserting new tab items. I have a collection of tabs, but when adding a new item, I need to insert DOM elements in two different areas. The problem is that Marionette.CollectionV ...

Problem related to permissions within a node.js package

Introducing my newly built npm module called emeraldfw, now available for public use. Here is a glimpse of the contents in my package.json file: { "name": "emeraldfw", "version": "0.6.0", "bin": "./emeraldfw.js", "description": "Emerald Framework ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Understanding how to extract a specific value key from a JSON object in Typescript while utilizing Angular can greatly

I'm currently facing a challenge in Typescript with Angular where I need to retrieve a specific value from a JSON constant. While I am aware of the performance implications, I am wondering if there is a more efficient way to access this value within t ...

Investigating Javascript compatibility problems with Firefox 4

In FF3.X and IE7 to 9, the code below is functioning correctly, but in FF4, there seems to be an issue. The following code is used in two different locations within my file: var args = "method=getoptions"; args += "&dr ...

A technique for adding a border to a Mat Card that mimics the outline of a Mat Form Field within a custom

I am faced with a unique design challenge where I am utilizing the MatCardComponent and each card contains a table. I would like to incorporate a floating label within the border gap similar to what is seen in MatFormField. https://i.stack.imgur.com/51LBj ...

What could be causing the uneven application of CSS padding when it is applied to a div that serves as the parent of an HTML form?

Padding has been added only to the top and bottom of a div. The padding attribute is displaying consistently for the form element, however, it is not behaving uniformly for the parent div of the form as illustrated in the image provided below. Output:- h ...

Prevent webpage from resizing when window dimensions change

Whenever I resize my webpage window, the elements start to pile on top of each other and it looks disorganized. For example, when I reduce the window size, YouTube just cuts off everything instead of stacking the images. How can I achieve a similar effec ...

Send the selected option from the dropdown menu to a different page

I am in the process of designing a unique shopping cart system where, upon clicking on the "add to cart" link, both the selected quantity from the drop-down menu and the product ID are transmitted to the addCart page. While I have successfully managed to p ...

Angular utilizing external parameter for Ajax requests

As a newcomer to Angular, I am eager to upgrade some old jQuery code with AngularJS. The task at hand is to extract a string from a span element, split it into two separate strings, and then use these as parameters in a GET request. I am dedicated to lea ...

Should I use a single CSS file or separate CSS files for each page?

As I construct my website pages, I often ponder whether it's best to utilize separate stylesheets for each page or to have one comprehensive stylesheet for the entire site. In terms of loading efficiency, wouldn't having individual files be more ...

What are the steps to implementing PNG masking using PixiJS?

I am currently working on incorporating a png sprite as a mask for another layer. I found a demo on the pixi.js official website and created this fiddle: https://jsfiddle.net/raphadko/ukc1rwrc/ The code snippet below is what I am using for the masking fu ...

Even after being removed, the input field in Firefox stubbornly maintains a red border

I have a project in progress that requires users to input data on a modal view and save it. The validation process highlights any errors with the following CSS snippet: .erroreEvidenziato { border: 1px solid red; } Here is the HTML code for the moda ...

Using JQuery to load a table and inject it with html()

I am looking to populate an HTML table within a specific div element. The HTML code is being loaded using the following jQuery function: $("#table_wrapper").hide(); $.get("<?echo base_url();?>schichtplan/employee_fields/"+plan_id+"true",function(da ...

Guide on Creating HTML Embeds for Multiple Selection Code Blocks

I need some help creating a feature similar to this: View Image Unfortunately, I haven't been able to locate any tutorials or code samples on how to implement multi-selectable language code blocks using HTML/CSS. My CSS knowledge is limited, and I r ...