Move a div element into another div element in HTML

I have been attempting to create a draggable green div that stays within the boundaries of another div with a border. Here is my progress so far.

Check it out here

Allow me to illustrate:

This is what I want

And this is what I don't want

The green div should be movable but constrained by the limits of the small white-bordered div in all corners, as shown above.

Answer №1

To properly constrain the movement of an element using jQuery UI's draggable function, you can utilize the 'containment' property. Below is an example explaining how to achieve this:

$(function() {
    $("#draggable").draggable({ 
        containment: [-100,-100,0,0]
    });
});

Pay attention to the 'containment' parameter values in the code snippet above. These values represent the offset or position (depending on context) of the area from its relative position where the '.draggable' element will be restricted to during dragging.

For instance, given the following HTML structure:

<div class="bigDiv">
    <div class="smallDiv" id="draggable">
    </div>
</div>

and corresponding CSS styles:

body {
    margin: 0;
    padding: 0;
}
.bigDiv{
    border: solid 1px black;
    position: absolute;
    top: 0;
    left: 0;
    height: 200px;
    width: 200px;
}

.smallDiv{
    opacity: 0.5;
    background-color: limegreen;
    position: absolute;
    width: 300px;
    height: 300px;
}

Based on the offset values of '.bigDiv' from its relative position (top: 0, left: 0), your 'containment' parameter should be set as [1st_param, 2nd_param, 3rd_param, 4th_param], with calculations involving container dimensions and offsets.

  • 1st_param - Leftmost offset from relative position (-100)
  • 2nd_param - Topmost offset from relative position (-100)
  • 3rd_param - Lowest left offset (calculated accordingly)
  • 4th_param - Lowest top offset (calculated accordingly)

For a visual demonstration, check out the Fiddle Demo. If further clarification is needed, refer to the complete code in action here, adjusting the position, width, and height values of '.bigDiv' and '.smallDiv' for different outcomes.

Answer №2

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

//if div1 is clicked, execute the following code
$("#div1").mousedown(function(){

$(window).mousemove(function(event) {

 var xPosition = event.pageX;//get the x position
 var yPosition= event.pageY;//get the y position
 $("#div1").css("left", xPosition);//set the left position of div1 to xPosition
 $("#div1").css("top", yPosition);//set the top position of div1 to yPosition

  //perform actions if coordinates exceed container limits
   if(xPosition > 450)
   {
      $("#div1").css("left", 450);
   }
   if(yPosition > 260)
   {
      $("#div1").css("top", 260);
   }
   //perform actions if coordinates are less than container limits
   if(xPosition < 0)
   {
      $("#div1").css("left", 0);
   }

   if(yPosition < 0)
   {
      $("#div1").css("top", 0);
   }
 });

});

});
</script>
</head>
<body>

<div id="div2" style="background-color:green;width:500px;height:300px; position:absolute;">

<div id="div1" style="background-color:red;width:50px;height:40px; position:absolute;"></div>
</div>

</body>
</html>

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

"Create a button in JavaScript that allows users to easily download a MySQL table

The website has been developed using node js/express, but there is a challenge in generating an URL to download the data from mysql table into a csv file. Is it feasible to accomplish this without relying on php? desirable outcome: "Download Data" "a sp ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Refreshing chosen value (html) utilizing buttons

In my code, I have a Select that allows me to choose the number of a chapter I want to display (see image): <select name="select" onchange="javascript:sliders[0].goTo(value);"> <?php for($i=1; $i<$row['nbChapitre']+1; $i++){ ?> ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Unable to export to Excel using TableTools feature

Trying to export a DataTable view to Excel using the TableTools plugin, but encountering issues with the "Excel" button not working. Without a step-by-step tutorial for guidance, here's the code used in a test HTML: <!DOCTYPE html> <html ...

jQuery functionality restricted to desktop devices

I am attempting to disable a jQuery function specifically for mobile devices. I found some instructions that seem helpful on this page. Unfortunately, following the instructions did not work for me. Here is the code snippet I have: var isMobile = /Androi ...

What is preventing me from utilizing global variables in distinct HTML and JavaScript files?

I am facing a perplexing issue with my HTML files, specifically index.html and lobby.html. Within main.js, which is loaded in index.html, I attempt to load lobby.html using window.location.href. Despite trying various methods to define global variables i ...

The dropdown menu is currently activated, but not the individual items within it

Is there a way to make the dropdown menu active when I click on an item, specifically making the word Services active? How can this be achieved? <nav class="navbar navbar-light navbar-expand-xl"> <a class="navbar-brand" hre ...

What is the reason behind Modernizr assigning a drag-and-drop class specifically to iOS devices?

I'm wondering why Modernizr assigns the draganddrop class to iOS devices. It seems challenging to drag and drop files in mobile Safari. Could this be a bug or intentional feature? ...

Interactive tool for crafting dynamic web experiences

I am in the process of developing a straightforward hosting website for my projects. However, I have noticed that many software options feature a split view for editing code and previewing changes, such as Dreamweaver. I am on the lookout for a live edito ...

Set the cursor in the textbox automatically when the page first loads

Is there a way to set focus on a text box when a page loads? I've attempted using the autofocus attribute but it hasn't worked for me. You can view my form here: http://pastebin.com/xMJfQkcs ...

Tips for incorporating a sticky toast notification in the ready state of a CI web application

Can you help me with adding sticky toast notifications to my CodeIgniter site's home page? I've tried a few things but it doesn't seem to be working correctly. <div> <p> <span class="description">To show a success ...

Conceal an element if the angular attribute does not contain any value

Currently, I am facing an issue with an image element in my project. The path for this image is being fetched from an attribute present on my angular object. However, if this imagePath attribute is empty, a broken image is displayed. I want to avoid rend ...

Transforming JSP style tags into CSS declarations

Within my JSP file, I have various tags that look like this: <style type="text/css"> #mask { display: none; cursor: wait; z-index: 99999; position: absolute; top: 0; left: 0; height: 100%; ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Contrasting the addition of an onClick listener through Jquery versus utilizing an HTML onclick attribute

I found this interesting piece of code that I want to share with you all: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.12.4.js"></script> <title> HelloWorld JQuery </t ...

Is there a way to effortlessly scroll an element when the CSS overflow property is designated as auto?

I need help with creating a testimonial section where two divs automatically scroll inside a fixed-height container. Currently, only one div is scrolling while the other remains static in my code. I have implemented JavaScript for automatic scrolling wit ...

Using Angular material to display a list of items inside a <mat-cell> element for searching

Can I use *ngFor inside a <mat-cell> in Angular? I want to add a new column in my Material table and keep it hidden, using it only for filtering purposes... My current table setup looks like this: <ng-container matColumnDef="email"> < ...

Blending HTML template and WordPress PHP file

I am facing a challenge while attempting to implement a Wordpress template on one of the pages of my website, specifically at http://www.windowblindshadeshutters.com/blog/. The blog has been successfully created, however, I am having trouble preserving our ...