Widget closes and div moves to the top using Jquery dragable feature

I'm currently utilizing Jquery-Ui for Jquery draggable on one of my websites. Here is the fiddle link: fiddle. I have the ability to add multiple widgets to the screen, which works well. However, when I close one and attempt to drag another widget, its position shifts to the top of the document. How can I prevent this from happening?

Below is my script:

var widgetId = 0;
$("#btnAddWidget").click(function () {
                $("#container").append('<div class="Widget" id="widget' + widgetId + '"><input type="button" class="close" id="btnclose' + widgetId + '" value="Close" /><input type="button" class="addgraph" id="btnAddGraph' + widgetId + '" value="Add Graph" /></div>');
                widgetId++;
                $(".Widget").draggable({
                    containment: '#container',                    
                    cursor: 'move',
                    start: function (event, ui) {
                        var Startpos = $(this).position();
                        if (Startpos.top < 0) {
                            debugger;
                            $(this).css("top", 0);
                        }
                    },
                    stop: function (event, ui) {
                        var Stoppos = $(this).position();                        
                        if (Stoppos.top < 0) {
                            debugger;
                            $(this).css("top", 0);
                        }
                    }
                });
                $(".Widget").resizable({ containment: 'parent', });
            });

            function setPositionToRelative(element)
            {

            }

            $(document).on('click', '.close', function (e) {
                e.preventDefault();
                $('.Widget').each(function () {
                    var top = $(this).position().top + 'px';
                    var left = $(this).position().left + 'px';
                    $(this).css({ top: top, left: left });
                }).css({ position: 'absolute' });

                $(this).parent().remove();

            });

Answer №1

If you prefer, you can include the following CSS code to adjust the positioning of the widgets at the top manually.

#container {
    height: 500px
}

Alternatively, you can use:

#container {
    min-height: 500px
}

Answer №2

I made a modification to your code snippet:

$('.Container').each(function () {
   var topPos = $(this).position().top + 'px';
   var leftPos = $(this).position().left + 'px';
   $(this).css({ top: topPos, left: leftPos });
}).css({ position: 'fixed' });

By removing this section of code, you should see the desired outcome you are seeking. This block was being triggered on close click and impacting the css properties of each .Container element in an unintended way.

Let me know if you need further assistance.

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

What is the best way to switch between different audio based on the currently viewed div?

I am working on a project where I need specific audio files to play depending on which div is currently in view on the website. While I was able to find resources related to playing different audio based on height locations of the site, my challenge lies i ...

Creating a sizable chart that spans across multiple pages

My PHP output generates an HTML table with size XL. I want to add a print button on the page that will automatically print out the table with correct formatting. Specifically, I hope to print the table horizontally with headers appearing on every printed ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Three.js ColladaLoader failing to display content on the canvas

I was working on a new project and noticed that everything seems to be loading correctly. I've been reading the Three.js documentation consistently to troubleshoot any issues, but unfortunately, none of my attempts have been successful so far. After ...

How can you hide the selectMenu in jQuery?

Currently, I am implementing jQuery's selectMenu feature on a select tag as shown below. $('#ddlReport').selectmenu() There are certain scenarios where I need to hide it, but I am struggling to find the right way to do so. The following a ...

Reordering table columns for better mobile display

I've been working on editing a newsletter for my client and I seem to have hit a roadblock... Here's an example of the table I'm working on https://jsfiddle.net/xocrqwLs/ The issue arises when viewing it on a mobile device, as it appears ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Instructions for transforming DOM information into a JSON format

I have multiple inputs within my document, as shown in the code snippet below. My goal is to create a string or JSON object using the input names and values. var arr= []; $('ul li input').each(function(){ let name = $(this).attr(' ...

Tips for correctly sizing and centering a DataTables table on a computer screen while ensuring that the header and data cells remain aligned

I have implemented a DataTables-enhanced HTML table for sorting and horizontal scrolling on tablets and mobile devices, which works well on smaller viewports. However, I am encountering issues with the desktop viewport: On desktop, my goal for the table ...

What is the best way to apply the same effect to multiple images without affecting the ones I haven't hovered over?

I am currently facing an issue with 6 images displayed in a table, 3 per row across 2 rows. I applied the "grow" effect to all the images but it seems like everything is moving around in a confusing manner. Does anyone have suggestions on how I can resolve ...

Utilizing Jquery to smoothly animate elements upwards, adjust the z-index, and then gracefully animate them

Looking for a more efficient way to achieve the desired functionality without repeating jQuery code and targeting individual divs: $(function() { $('.img-spot-wrap').hover(function() { var $foo = $(this); ...

When using AngularJS, compatibility issues may arise with loading ASP.Net MVC Partial Views triggered by a @Ajax.ActionLink()

Currently, I am facing an issue while trying to incorporate AngularJS into ASP.Net MVC. The problem arises when AngularJS does not seem to work in the rendered view called from @Ajax.actionLink(). Below is a snippet of the code that I have experimented wit ...

Learn the steps for creating smooth transitions between two HTML pages

Can anyone help me achieve a transition effect between HTML pages when clicking on menus or submenus? I want the page to open with a smooth transition. Thank you in advance for your guidance. I found a link that shows how to add a transition effect within ...

choose the initial element within a class

Seeking a way to target the first element within each group of the same class? Consider the following scenario: <div class="group"> <div class="element"></div> <div class="element"></div> <div class="element"&g ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

The issue of receiving null data at the controller side is a common problem with jQuery

I'm encountering an issue with my Ajax post where the data always shows up as Null on the Controller side. Can someone please assist me? Here are the relevant code snippets: **Model:-** public class UpdateProxyTracker { public string ...

Error: Page not found - The requested URL localhost:8080/login could not be located

My first time trying to utilize ajax and json is resulting in a 404 error. The issue seems to be that /login cannot be found even though I have defined LoginServlet with the url pattern /login in web.xml. Here is the code from web.xml: <servlet> ...

Attempting to fill a template using ngfor, wherein the initial 2 elements are displayed in a row

I am attempting to complete a task where, using an ngFor directive to iterate through an array, I need to display the first 2 elements in a row and the remaining elements in a descending column. It should look like this: first second third fourth fifth ...

Querying the Twitter API for search results

Is there a limitation on including lists in Twitter API calls? My PHP code is using a search query API to fetch a feed. Whenever I try to include something like: '?q=%23swag+list%3Ayoutube%2Fmusic' I only receive results from: '?q=%23swa ...

How can I make a div take up the entire height of its parent column using Bootstrap?

I need the div with the red border to match the height of the green div on the right. I'm using Bootstrap 4 for this layout! I've experimented with display: flex and flex-grow, and also tried placing the border on the column (which achieves the ...