Utilizing CSS transitions in tandem with jQuery mousemove

Currently, I am developing a game that involves clicking and dragging using jQuery. Within the red game div, when you click an object appears that can be dragged around. To view a demonstration of this functionality, you can visit the following fiddle link:

https://jsfiddle.net/r9pet266/6/

In order to achieve a smooth experience, I added a CSS transition property to the block to create a slight delay between mouse movement and block movement.

The issue arises when selecting outside the game div; subsequent clicks and drags inside the area become jumpy. Can anyone explain why this occurs?

HTML

<div id="outer">
  <div id="game"></div>
  <div id="instructions">
    1. Click and drag inside the red box --> smooth <br>
    2. Click on the green <br>
    3. Click and drag inside the red box --> jumpy
  </div>
</div>

CSS

#outer {
  height: 500px;
  background: green;
}

#instructions {
  position: absolute;
  top: 350px;
  left: 100px;
}

#game {
  position: relative;
  display: inline-block;
  width: 300px;
  height: 270px;
  background: red;
}

.block {
  transition: 100ms;
  position: absolute;
  width: 80px;
  height: 80px;
  background: black;
}

JavaScript:

var $block;

$('#game').mousedown(function (e) {
  e.preventDefault();

  $block = $('<div>');
  $block.addClass('block');
  updatePosition(e);
  $('#game').append($block);

  $('#game').mousemove(updatePosition);

  $(window).one('mouseup', function () {
    $block.remove();
    $('#game').off('mousemove');
  });
});

function updatePosition (e) {
  $block.css('top', e.pageY - 45 + 'px');
  $block.css('left', e.pageX - 45 + 'px');
}

Answer №1

Once the cursor moves beyond the boundaries of the red and black box, it exits the realm of #game, causing the mousemove event handler to cease functioning. To rectify this issue, you should attach the mousemove event handler to the document instead of #game. Here is how you can do it:

$(document).mousemove(updatePosition);

For a demonstration, check out the updated JS Fiddle.

Answer №2

// update
$('#game').mousemove(updatePosition);
// change to 
$(window).mousemove(updatePosition);

The block's movement halts because the mouseover event listener is only triggered when passing over the red box.

The jumping effect occurs due to event bubbling. Since the black box is a child of the red box, hovering over the black box also counts as hovering over the red box. (Refer to the link for a detailed explanation.)

Answer №3

Solution:

$('#container').click(function (event) {
    event.preventDefault();
});

By preventing the default action on the element, it resolved the issue of erratic behavior.

Check out the updated code snippet here:

https://jsfiddle.net/abc123xyz/9/

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

JustGage error: Unable to locate element with ID 0 in AngularJS

I developed a custom directive for the JustGage plugin, here is how it looks: function justGage() { return { restrict: 'E', replace: true, scope: { universalId: '@', ...

The functionality of the Jquery expand and collapse menu appears to be malfunctioning

I'm currently working on implementing a sidebar menu navigation that expands and collapses when the user clicks on the menu. Additionally, I want the menu to remain expanded if a link in the sub-menu is active when the page loads. Below is the code s ...

Capitalize the host name from both the current HTTP request in the HttpContext object and the

Curious inquiry, I must admit, but nonetheless, is it possible for HttpContext.Current.Request.Url.Host or window.location.host to return a value in uppercase? Would it be advisable to utilize .toLowerCase and .ToLower methods to ensure everything goes s ...

Angular 2 operates in a separate thread, processing custom serializable objects

Is there a way to efficiently handle potentially long computations, such as parsing huge JSON responses, in a non-blocking manner? I experimented with using the multithread.js library for background work using web workers. However, this library requires p ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Changing the response body before calling res.send() in ExpressJS

Currently, the application I am working on utilizes Express. My goal is to intercept the response before it is sent and modify it for JWT purposes. With numerous endpoints in this application, I am looking for a way to achieve this without creating a custo ...

What is the best way to obtain a date in the format of yyyy_mm_dd from a datepicker tool?

I am working with 2 datepickers that have similar structures, but different names. The first one has the id "fecha_1_1" and the second one has the id "fecha_1_2". <div class="col-sm-3"> <p>Desde</p> <div class="f ...

I am struggling to assign the height style attribute to a div element

I have created the code below where I am attempting to set a div to 'display: flex' and include two divisions, one with a width of 200px and the other with a width of 100%. <div style="clear:both;display:flex; height: 100%;"> <div ...

"Transferring a C# dictionary into a TypeScript Map: A step-by-step

What is the correct way to pass a C# dictionary into a TypeScript Map? [HttpGet("reportsUsage")] public IActionResult GetReportsUsage() { //var reportsUsage = _statService.GetReportsUsage(); IDictionary<int, int> te ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

After 60 seconds, the AJAX call is returning a 200 status code despite the fact that the server-side process is still

When implementing an AJAX call, I followed this structure: $.ajax({ url: 'download', type: 'POST', data: JSON.stringify(postData), cache: false, contentType: 'application/json;charset=UTF-8' }) . ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Utilizing displacement mapping in three.js

Currently, I am using a grayscale image as a bump map for my model. The model consists of an .obj file paired with the corresponding .mtl file for UV mapping. Below is the code snippet that I am utilizing: // Load material file var mtlLoader = new THREE.M ...

The attribute 'includes' is not found in the data type 'RouteRecordName'

Currently experiencing difficulties with using array includes in conjunction with TypeScript. Numerous sources suggest adding the ES2016 lib option (or higher) to tsconfig.json. Despite trying various combinations of lib and target settings, none have prov ...

Issue encountered when sorting sequelize query by date in ascending sequence

My challenge is to arrange a sequelize query in ascending order by date. Specifically, I am focusing on sorting the results of the model: ExamScore (referred to as student_score). I've specified the column "updated_at" for ordering and the method of ...

Creating a customized ASP.NET AJAX control that utilizes templating for dynamically showing or hiding items within a placeholder

I am dealing with a custom templated control (toolbar) that includes a custom user control (button). The button utilizes jQuery for styling and managing various states, postbacks, and non-postbacks. Within this setup, some of the buttons are initially hid ...

Tips for shifting the cursor slightly to the right within an Input field

I created a div with an input field inside. I set the input field to autofocus, so when the page loads, the cursor is automatically focused on the input field. However, the cursor is touching the border of the input field, making it hard to see clearly. ...

Converting an image to a link is not effective

Currently facing a challenge trying to turn a list of images into clickable links. Here's how I have set them up in my HTML code: <a href="plantvb1.html" class="plant1"><img src="img/plnt1_.png"></a> and this is how they are style ...

Show an Unordered List in a Horizontal Orientation

I'm having trouble getting my Subnav list to display horizontally. Can anyone offer a solution to this issue? http://jsfiddle.net/nategines/9bued/10/ ...

.val() function not returning the expected value

In the code below, I have a change event listener for a select box: $('#reg-phone-type').change( function() { console.dir($(this)); console.log("$(this).val():" + $(this).val()); if( $(this).val == 'work' ) { // ...