Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container.

To better illustrate my problem, you can view a demo on Fiddle. Here is the code snippet:

$(document).ready(function() {
  $(".MENU").draggable({
    containment: ".MENU-CONTAINER",
    snap: ".MENU-CONTAINER",
    snapMode: "inner",
    snapTolerance: "16",
    scroll: false
  });
});
* {
  box-sizing: border-box;
}

body {
  background: hsla(0, 0%, 100%, 1.00);
}

.MAIN {
  padding-top: 32px;
  padding-left: 64px;
  width: 100%;
  height: 100%;
}

.MENU-CONTAINER {
  position: fixed;
  width: calc(100% - 64px);
  height: calc(100vh - 64px);
  background-color: hsla(120, 100%, 25%, 0.3);
}

.MENU {
  position: fixed;
  bottom: 32px;
  right: 32px;
  width: 128px;
  height: 64px;
  background: hsla(0, 0%, 0%, 1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div class="MAIN">
  <div class="MENU-CONTAINER">
    <div class="MENU"></div>
  </div>
</div>

My question is, how can I ensure that this element remains contained within its container even after resizing the viewport?

Answer №1

Implement reloading functionality after resizing the window

$(window).resize(function(){
    location.reload();
});

Demo:

$(".ELEMENT").draggable({
  containment: ".CONTAINER",
  snap: ".CONTAINER",
  snapMode: "inner",
  snapTolerance: "16",
  scroll: false
});

$(window).resize(function(){
    location.reload();
});
* {box-sizing: border-box;}

body {background: hsla(0, 0%, 100%, 1.00);}

.MAIN {
  padding-top: 32px;
  padding-left: 32px;
  width: 100%;
  height: 100%;
}

.CONTAINER {
  position: fixed;
  width: calc(100% - 64px);
  height: calc(100vh - 64px);
  border: 1px solid blue;
}

.ELEMENT {
  position: fixed;
  bottom: 32px;
  right: 32px;
  width: 128px;
  height: 64px;
  background: hsla(0, 0%, 0%, 1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="MAIN">
  <div class="CONTAINER">
    <div class="ELEMENT"></div>
  </div>
</div>

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

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

Utilizing React JS to Activate the Glyphicon Calendar Icon on Click

Could someone please advise on how to make the calendar glyphicon activate the datetime picker upon clicking? I have a button currently but it is not functional. I've been searching for React-specific solutions without success. <div className={cla ...

Aligning divs, prevent duplicate HTML within multiple divs

Currently, I am attempting to troubleshoot a jsfiddle issue. The main problem lies in my desire for the first two divs (with class="fbox") to be aligned next to each other on the same level. Furthermore, I am looking to enable dragging the image into the ...

Fullscreen overlay or pop-up display

I have a website with images and iframes displayed within a fancybox. Everything is functioning properly, but now the website's requirement is to have a fullscreen overlay like on the usatoday website. Take a look at for reference. When clicking on ...

Is it possible to reverse SEF URLs using jQuery?

I'm currently employing this script to generate SEF URL strings: Replace spaces with dashes and convert all letters to lowercase using JavaScript I've been curious if there exists a method to reverse this process using jQuery? For instance: th ...

Is it possible to determine HTML5 Context Menu Support using JavaScript?

While reviewing the Modernizr documentation, I couldn't find any information on creating a menu element and then checking its existence. However, I am concerned that even if the browser supports this, it may not support the type context. Do you have a ...

Obtain the script's event feedback from the WebView and transfer it to React Native

My HTML script is used to display a module, but I encountered an issue with the eventHandler not responding. How can I ensure that the eventHandler in Web View triggers responses? I am not receiving any logs for the onSuccess, onError, or onClose methods w ...

A tutorial on allowing a background element to capture the click event triggered by a foreground element

Within a container div, I have a background and foreground div. I want the click event on the foreground div to be passed through to the background div for handling the event. How can this be achieved in Angular 2+? Here is an example structure of my div ...

Utilize the directive method within the transcluded content by making a call

Trying to call a method within a directive from transcluded content. The structure of my HTML is: <typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer"> <ul> <li ng-click="select ...

Unable to dismiss a Popup Dialog Box using Selenium Webdriver in Python(Element is not visible at the moment and cannot be interacted with)

I am facing difficulty closing a jQuery dialog box using Selenium Webdriver. See my code below. I am currently using Selenium WebDriver version 2.44.0 and Firefox version 33. Any suggestions would be greatly appreciated. from selenium import webdriver fro ...

Even with manual installation, the npm package still encounters dependency errors

Having trouble implementing the Imgur package from NPM into my Angular web app. The installation and import seemed to go smoothly, but when initializing a variable with the package, I encounter compile errors pointing to missing dependencies like 'cry ...

Accessing data stored in XML or JSON files from a local server

I am currently working on loading a list of coordinates for a Google map from either an XML or JSON file, both of which are hosted in the same directory on my local test server. So far, I have used a hard-coded JSON object to load map coordinates for tes ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

The list of suggestions is not populating when triggered by the 'change' event

Using the typeahead jquery plugin in Rails 4.2.4 for autocompletion of lists has a specific issue: The typeahead list only loads with custom parameters the first time; it doesn't reload the second time. Here's an example code snippet from the vi ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Implementing auto-complete functionality for a text box in an MVC application using jQuery

After incorporating code for auto completion in a text box using AJAX results, the following code was utilized: HTML: <div class="form-group col-xs-15"> <input type="text" class="form-control" id="tableOneTextBox" placeholder="Value" > ...

How to find the length of an array in Node.js without utilizing JQuery

Is it possible to determine the length of the Dimensions array in nodejs? The array can have 1 or 2 blocks, and I need to write an if condition based on this length. Since this code is inside an AWS-Lambda function, using JQ may not be an option. For exam ...

Tips for Adding Items to an Infinite Loop

Could you please review This Demo and advise me on how to continuously load items into the ul list in an endless manner? Currently, I have this code set up to display the list but I want it to keep adding new items to the end every time. var item = $(". ...

Retrieve the URL of an image located within an <li> tag within a jQuery selector item array

I am currently using a jQuery slider plugin to display images, and I am attempting to retrieve the URL of the current image when a button is clicked. The slider functions by showcasing all the image slides as list items in a continuous horizontal row. It ...