Positioning a div within another div using values from a textarea - a step-by-step guide

Check out this script I have:

HTML

<div id="left">
  <div>Orange Div</div>
  <div>
   <div class="left_text">top</div>
   <div class="left_text">left</div>
    <textarea class="count2"> </textarea>
    <textarea  class="count1"> </textarea>
   <div style="clear: both;"></div>
   <button id="getText1">Move</button>
  </div>
</div>
<div id="red_div">
 <div id="green_div">
  <div id="orange_div">
   <h3>Orange Div</h3>
  </div>
 </div>
</div>

CSS

#left{
width: 150px; 
height: 80px; 
float:left;}

.left_text{
color: red;
height:20px; 
width:50px; 
float:left;}

textarea.count1, textarea.count2 {
color: red; 
height:20px; 
width:50px; 
float:left;}

#red_div{
margin: auto; 
width: 300px; 
height: 450px; 
float:left;
border: 1px solid ccc;
background-color: red;}

#green_div { 
width: 300px; 
height: 200px; 
float: left; 
display: block; 
position: relative; 
background-color: green;
border: 1px solid ccc;
margin-top: 100px;}

#orange_div { 
width: 100px; 
height: 100px; 
float: left; 
font-size: 16px;
font-family: Arial;
background-color: orange;} 

JQUERY

 $( "#orange_div" ).resizable().draggable({
  containment: "#green_div",
   scroll: false,
    drag: function(event) {
        o = $(this).offset();
        p = $(this).position();
        $('.count1').html(p.left);
        $('.count2').html(p.top);
    }
});

function updateCoordinate(newCoordinate) {
    $(".count1").text(newCoordinate);
    $(".count2").text(newCoordinate);
}
    $("#getText1").click(function () {
    $("#orange_div").offset({ 
    top: $('.count2').text(), 
    left: $('.count1').text()
    });
}); 

The demo is here:

http://jsfiddle.net/emilsifu/zPHhp/4/

I'm trying to position the orange div inside the green div when values are entered in the textarea on the left. The orange div should be draggable.

Currently, it seems to be positioned from the top left corner instead of where intended.

Your assistance is greatly appreciated!

Answer №1

Utilizing the jQuery val() function in place of html() and text() functions along with incorporating @jdpatel's solution above appears to resolve the issue effectively. Given that it involves a text area, it is deemed safer to solely manage the value of the field.

$(document).ready(function()
 {

  $( "#orange_div" ).resizable().draggable({
  containment: "#green_div",
   scroll: false,
    drag: function(event) {
        o = $(this).offset();
        p = $(this).position();
        $('.count1').val(p.left);
        $('.count2').val(p.top);
    }
});

function updateCoordinate(newCoordinate) {
    $(".count1").val(newCoordinate);
    $(".count2").val(newCoordinate);
}
    $("#getText1").click(function () {
    $("#orange_div").offset({ 
    top: $('.count2').val(), 
    left: $('.count1').val()
    });
}); 

});

/EDIT/

Upon retesting shortly after, the behavior changed once again without any apparent reason. Although I have managed to keep it consistently within the green box, preventing it from attaching to the body, it now seems that the applied left value only takes effect after completing the dragging action. Despite trying to identify differences in CSS or classes, the issue remains unresolved until dragging occurs.

    $(document).ready(function(){

        $( "#orange_div" ).resizable().draggable({
        containment: "#green_div",
        scroll: false,
        drag: function(event) {
            o = $(this).offset();
            p = $(this).position();
            $('.count1').val(p.left);
            $('.count2').val(p.top);
        }
    });

function updateCoordinate(newCoordinate) {
    $(".count1").val(newCoordinate);
    $(".count2").val(newCoordinate);
}
$("#getText1").click(function (event) {
   event.preventDefault();
    $("#orange_div").css({ 
        top : $('.count2').val() + "px",
        left : $('.count1').val() + "px"
    });
}); 

});

Answer №2

If you want to enhance the functionality, include the additional JavaScript provided below:

Then, within the document ready function, write the following functions which will make everything work seamlessly:

$(document).ready(function() {

  $( "#red_box" ).resizable().draggable({
    containment: "#green_box",
    scroll: false,
    drag: function(event) {
        o = $(this).offset();
        p = $(this).position();
        $('.x-coordinate').html(p.left);
        $('.y-coordinate').html(p.top);
    }
});

function updatePosition(newPosition) {
    $(".x-coordinate").text(newPosition);
    $(".y-coordinate").text(newPosition);
}

$("#moveElement").click(function () {
    $("#red_box").offset({ 
      top: $('.y-coordinate').text(), 
      left: $('.x-coordinate').text()
    });
}); 

});

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

AngularJS's ng-click function seems to be malfunctioning

Currently, I am in the process of learning angularJS with the help of the book titled "Learning Web Development with Bootstrap and AngularJs." One challenge I am facing is creating a ng-click functionality for a button in my project. Unfortunately, when I ...

Combining Isotope, infiniteScroll, Wordpress, and Bootstrap is a powerful formula

Attempting to accomplish a rather straightforward task... The scenario involves a custom-post-type archive page in Wordpress where I display ten posts per page with pagination. I utilize isotope js for div packing and employ next_posts_link() to create a ...

Replicating the existing div content into a textarea

I wanted to create a tool for my workplace as a learning project in html, CSS and JS. It's a timer that tracks how long I spend on tasks. Currently, I have the timer resetting itself but I'm facing an issue where the paused time is not being log ...

When the checkbox is not selected, the content on the page will revert back to its original state

Is there a way to dynamically change content on a page when a checkbox is checked, and revert it back when the checkbox is unchecked? I don't want to manually set each element's value to default in JavaScript and CSS. <div class="switch&q ...

Tips for evenly spacing Navbar items in Bootstrap 4

Designing a navigation system using Bootstrap for my website. I'm struggling to figure out the best way to space out the navigation link elements on my navbar so that it looks good on both desktop and mobile screens. This is my current navbar code: ...

What could be causing the no-repeat functionality to fail on these background images, and what steps can be taken to prevent the list text from overlapping with the image?

UPDATE EDIT. There is still an unresolved issue with this problem. Although setting the background to no-repeat fixed the image repetition problem, the list item text still overlaps the background image and there is an extra tick to the left. Please refer ...

Ensure that the text box inside the div adjusts its size in accordance with the dimensions of the window, as the div is already designed

As a novice in HTML and jQuery, I am currently working on creating a portfolio site for a school project. One of the challenges I have encountered is designing a graphic that includes a text box within a resizable div element. My goal is to prevent excessi ...

How can I eliminate a value from a hidden field using jQuery autocomplete functionality?

I am facing an issue with a page that contains two input fields: users_list and users_ids. The jQuery autocomplete feature is utilized to auto-populate the users_list. The users_ids field is hidden. When a user is selected and added to the users_list, thei ...

Best practices for evenly distributing images within a navigation bar?

Within a horizontal navbar, I have various small images that are currently spaced out with different intervals between them. Each image has its own unique spacing from the others. I am looking to achieve consistent spacing between each image in this horiz ...

Looking to utilize jQuery AJAX and PHP to submit data?

I have encountered an issue with inserting data into the database using this code. I have double-checked my PHP code and it seems to be correct. Can anyone help me identify what might be causing the problem? $(document).ready(function() { $("#submi ...

Bootstrap - A collapsed navigation button that remains fixed without the rest of the navbar

I'm currently working on a responsive drag and drop game that utilizes Bootstrap and jQuery UI. Within the game, I have implemented a collapsible navbar at the top of the page. To optimize space for buttons at the bottom, I am looking to hide the nav ...

Discovering elements with multiple classes using watir-webdriver

In this scenario, let's consider an element like the one below: <div class="first_class second_class"></div> Now, we can locate it by its classes using the following methods: browser.div(class: 'first_class') browser.div(class ...

Retrieve the initial image link from a blogger's post in cases where it is not being stored on the Blogger platform for use in related

I am currently using a hosting service to store the images that I include on my blogger platform. However, I have encountered an issue where blogger does not automatically fetch the image url to use as the thumbnail when the image is hosted externally. C ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Attempting to align two distinct divisions next to each other

Here is the updated code snippet: <Grid container justify="space-between" alignItems="flex-start" direction="column" xs spacing={5} style={{ padding: 10, }}> <ParamSelection/> { state.select ...

html5 Showing and hiding div elements

Here is a snippet of code to consider: @using App.Models @model App.Models.AllPeopleViewModel @{ ViewBag.Title = "Index"; } <html> <head> </head> <body> @foreach (Customer person in Model.Content) { <div class=&qu ...

Images obscure dropdown menu

The issue I am experiencing with my blog is that the dropdown menu is appearing behind the image slider on the main page. You can see it here: Can anyone offer guidance on how to prevent this from happening so that the dropdown menu is not obscured? Just ...

Using AJAX and PHP to input data into the database repeatedly

Need help inserting multiple values into a database using Ajax and PHP. Currently, the code only inserts one value and I can't figure out why. PHP Code: $content = $_POST['content']; $text = $_POST['text']; mysql_query("inser ...

Utilizing nested flex containers with overflow-x property

I'm looking to set up a layout with 2 columns side by side. The first column should have a fixed width of 200px, while the second column should take up the remaining space on the screen. Additionally, I want the content in the second column to auto-sc ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...