Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the placeholder.

Here is my code setup:

HTML:

<div class="sortable">
    <div class="item"></div>
</div>
<div class="sortable"></div>
<div class="sortable"></div>

Javascript:

$(".sortable").sortable({
    connectWith: ".sortable",
    over: function(event, ui){
        //add class .hover to list
    },
    change: function(event, ui) {
        //style placeholder
        ui.placeholder.css({
            visibility: 'visible',
            background: '#EEE'
        });
    }
});

Check out the demo here

Answer №1

After consulting Alteyss's suggestion, I have made adjustments to style the parent item by including additional lines for events such as over, stop, and out:

$(".sortable").sortable({
    connectWith: ".sortable",
    stop: function(event,ui){
        $('.sortable').removeClass('hover');
    },
    over: function(event,ui){
        // Adding class .hover to list
        $('.ui-sortable-placeholder').parents('.sortable').addClass('hover');
    },
    out: function(event,ui){
        $('.ui-sortable-placeholder').parents('.sortable').removeClass('hover');
    },
    change: function(event, ui) {
        // Styling placeholder
        $('.ui-sortable-placeholder').css({
            visibility: 'visible',
            background: '#EEE'
        });
    }
});

Check out the updated demo here.

Answer №2

Another method for customizing the placeholder style :

When you drag a box, you'll notice a tag with a class associated with the placeholder:

ui-sortable-placeholder

Create a unique class to override the default styles:

.ui-sortable-placeholder
{
  //Custom Style Here
}

Edit: Applying the hover effect

Implement a function in jQuery to manage the hover class and execute it within the event parameters:

    // Your function
    var addClass = function (jQueryElement, add) {
        // Add or remove the class based on the boolean value
        if (add) {
            //Adding class using addClass function from jQuery
            $(jQueryElement).addClass("hover");
        } 
        else {
            //Removing class using removeClass function from jQuery
            $(jQueryElement).removeClass("hover");
        }
    }

    // Plugin Setup
    $(".sortable").sortable({
        connectWith: ".sortable",
        over: function(event,ui){
            var elementsToChange = $(".ui-sortable-placeholder").parents(".sortable");
            addClass(elementsToChange, true);
        },
        out: function(event,ui){
            var elementsToChange = $(".ui-sortable-placeholder").parents(".sortable");
            addClass(elementsToChange, false);
        },
        stop: function(event,ui){
            addClass(".sortable", false);
        },
        change: function(event, ui) {
            //Styling the placeholder
            ui.placeholder.css({
                visibility: 'visible',
                background: '#EEE'
            });
        }
    });

Check out this cool Fiddle!

Explore more events in the documentation here : http://api.jqueryui.com/sortable/

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

Can you verify the standard behavior when importing index.js using create-react-app?

I'm trying to wrap my head around why, when using create react app, if a folder contains an index.js file and you want to import it, you only need to specify the folder name. I've been wondering where this default behavior is configured to autom ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

Capturing form data using jQuery and assigning it to a JavaScript variable

The code I currently have is set up to prevent the normal form submission and instead fetch the desired output from an API. However, my goal is to then store this data as a variable so that a button click can redirect to it (the output data being a URL). ...

Using Typescript: How to access a variable beyond the scope of a loop

After creating an array, I need to access the elements outside of the loop. I am aware that they are not in the scope and using 'this.' before them does not grant access. colIdx = colIdx + this.columns.findIndex(c => c.editable); this.focusIn ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

Determining the best times to utilize Grid items for alignment and justification versus when to avoid using them

I am wondering about the appropriate use of Grid item in order to utilize the props of the Grid container such as justify or alignItems. I initially thought that these attributes could only be applied to the Grid item within the Grid container, but my exam ...

Breaking down a number using JavaScript

Similar Question: JavaScript Method for Separating Thousands I'm looking to find a way to separate numbers by a thousand using JavaScript. For example, I would like to turn "1243234" into "1 243 234", or "1000" into "1 000" and so on. (sorry for ...

What could be causing the background color not to change on the HTML page with Bootstrap?

Learning html, bootstrap, and css styling can be a confusing endeavor. Sometimes things don't work as expected, like changing the background color. Despite following what seems like a simple solution after googling, the background color remains unchan ...

Is there a way to move the cards to the next line within a wrapper when the screen size is reached?

My goal is to showcase multiple elements in cards, obtained from my routing system, much like how I'm setting up my sidebar (which is functioning correctly). I have all the titles and icons ready, and the linking works seamlessly. This is where I&apo ...

Utilizing Jquery for JSON Data Parsing

I have some JSON data that looks like this: {"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]} In my JSP page, I&a ...

jquery method for choosing the first character of the HTML DOM

What is the best way to select the first character in HTML DOM using jQuery? I attempted to use $('#pcode')[0]; but it did not return the first value. Instead, when I tried to print it, I received [object HTMLInputElement]. How can I correctly se ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Tips for passing parameters in the $http GET request to transmit information from a dropdown menu using AngularJS

In the modal window I have for creating a new object, there are three forms: 1) a simple input to create "Name"; 2) A dropdown with "Types"; 3) A dropdown with "Ids". The issue arises when trying to send the data after filling out all the forms. An error o ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

Unable to modify the CSS properties of the titlebar in jQuery UI dialog

Is there a way to modify the background color of a jQuery UI dialog titlebar? Here is the code I am using: jQuery("#divId").dialog({ title: 'Information' }); jQuery("#divId .ui-dialog-titlebar").css("background-color", "red"); For m ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

The alignment of Flex Divs is off despite having identical heights

I'm facing an issue where divs are not staying at the top of their parent div if the image they contain does not have the same height as the others. Within my navbar, I have icons of varying sizes placed inside divs using display: flex to vertically ...