Alter the element's class during drag and drop操作

While in the process of dragging an element, I want to dynamically change its class or any CSS property based on its position. Here is what I have achieved so far:

https://jsfiddle.net/twfegqgc/

The issue I am facing is that the class changes only when the element passes halfway through the window, but it should also change when it reaches the end of the window width.

HTML

<div id="sun" class="yellow"></div>
<div class="position"></div>
<div class="window"></div>

JS

var sun = $("#sun");

sun.draggable();

$("#sun").bind("drag", function(event, ui) {
    var halfWidth = $(window).width() / 2;
    var left = $(this).offset().left + 100;
    var windowWidth = $(window).width() - 200;

    $('.position').html(left);
    $('.window').html(windowWidth);

    if(left > halfWidth) {
        sun.removeClass('yellow');
        sun.addClass('red')
    } else if (left == windowWidth) {
        sun.removeClass('red');
        sun.addClass('black')
    }

});

I am attempting to address another query with my current task.

Answer №1

The issue lies within the "if else" statement. Once you pass the mid-point, you will always trigger the first if statement. Removing the "else" condition will resolve the problem.

 if(left > halfWidth) {
    sun.removeClass('yellow');
    sun.addClass('red')
}


if (left == windowWIdth) {
        sun.removeClass('red');
        sun.addClass('black')
    }

For a functional solution, see this live demo: fixed solution

Update: To ensure functionality in all directions, additional conditions should be added to the if else statements:

if(left < halfWidth) {
    sun.addClass('yellow');
    sun.removeClass('red')
} else
if(left > halfWidth && left <= windowWIdth) {
    sun.removeClass('black')
    sun.removeClass('yellow');
    sun.addClass('red')
} else
if (left >= windowWIdth) {
    sun.removeClass('red');
    sun.addClass('black')
}

For an updated and improved solution, view this working example: updated solution

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

I am having trouble locating the ajax json data on the server

I am facing an issue with sending data from jQuery on the client-side to a CodeIgniter controller. Here is my code snippet: var data = { "value" : value, "message" : message }; console.log(postData); $.ajax({ type: "POST", url: "my_contr ...

Unable to stream data on React client app at the moment

I am currently developing a React application that requires a continuous response stream. To illustrate my situation, let's consider a scenario where I have an endpoint that sends back a number every second. In this case, I am utilizing Flask: def str ...

Experience a captivating Bootstrap 4 drop menu animation that emerges from beyond the borders of the page

I have a row that contains two divs, one with col-md-11 and the other with col-md-1. Inside the col-md-1 div, there is a dropdown that I want to animate. I am using animate css for the animation, but the issue is that the slideInRight animation starts from ...

Designing a touch-friendly scrollable space without traditional scrollbars

Looking to create a horizontal scrollable area for touch devices using just CSS. The current setup includes: .wrapper { position: absolute; left: 0; top: 0; right: 0; bottom: 0; width: 100%; height: 100%; overflow-x: scroll; overflow-y: ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

Instructions on incrementing a value in an object by 1 when the left mouse button is clicked on a button, and decrementing by 1 on right click

Being fairly new to html, I'm encountering difficulties with incorporating scripts in html. I have learned javascript on the csp code.org course and am currently self-teaching html. Although I understand javascript, I am unsure about which tags and ht ...

Instructions on creating an individual DropdownIndicator component with React-select for the purpose of reusability in different sections of the project

The code below functions properly when the DropdownIndicator component is kept in the same file. However, I am interested in separating DropdownIndicator into its own file so that it can be reused. This way, it can be used as a separate component and incl ...

What is the process for enabling a Submit button and updating its value following a successful Ajax response within a Django environment?

My current project involves using Django as the web framework. I am in the process of setting up an AWS lab or AWS account. To avoid multiple submissions, I have disabled the Submit button once the user enters information such as lab name, CIDR block, etc. ...

Traversing tables with JQuery's nextUntil function

I have a calendar table where I need to highlight the range from the pickup date, maybe 10 Feb, to the set date of 20 Feb. <tr class="rd-days-row"> <td class="rd-day-body rd-day-disabled">09</td> <td class="rd-day-body">10& ...

What could be causing the issue where Ruby on Rails date picker isn't updating the database? Any suggestions for troubleshooting

On my checkout page, I want to incorporate a form with 3 delivery choices using a date picker. Although I have successfully implemented the form on the page by using code from another site, I am facing an issue where the selected dates are not being store ...

Issue with value not updating following second ajax request

My project involves making an ajax call to render out a shopping cart using jQuery. function showShoppingCart() { $.ajax({ url: 'functions/show-cart.php', type: 'POST', dataType: 'json', }) ...

Contrasting angular.fromJson and $scope.$eval in their utilization of a JSON string

When working with my angularjs applications, I typically parse JSON strings using the angular.fromJson method: var myObject=angular.fromJSON(jsonString); However, it seems that achieving the same result is possible by utilizing $scope.$eval: var myObjec ...

Is it possible to employ a For loop with a Nodelist?

I have a unique HTML code structure that resembles a tree. My goal is to traverse the NodeList and assign specific classes to nodes that have children. Here's a snippet of the code: <li id='test' class="parentNode"> <button class ...

React and Express are two powerful technologies that work seamlessly

Here lies the contents of the mighty index.html file <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <s ...

Using Vue.js: Invoking a Function from a Different Component

Here is the HTML snippet from Component1 <component2></component2> This is the <script> block from Component1 export default { methods: { fetchData() { ... } } } Now, I want to call the method fetchData() in Compon ...

Ensuring the accuracy of checkboxes in a loop through verification

How can I ensure that at least one checkbox is selected before allowing the user to move on to the next page using JavaScript with a form structure like this? echo "<form method=\"POST\" action=\"confirm.php\">"; $query = mysqli_ ...

Looking for a quicker loading time? Opt for a shortened version of CSS

Most of the images on my website are optimized using sprite sheets, where multiple images are combined into one file to enhance user experience. This method reduces the number of server requests for individual images. However, I'm facing an issue whe ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

issue with adding string to listbox using angularjs

When attempting to add the string "New" to a list box, it is being inserted as "undefined". $http({ method: 'GET', url: 'http://xxx/api/Maintenance/GetAllFilteredItems', params: { Pt_Id: PtId} ...

Is it possible for Bootstrap to hide a grid column on extra small screens by setting its column width to zero?

Is there a specific Bootstrap class that allows me to hide a grid column for certain screen sizes without using media queries and the "display:none" style? ...