jQuery Dragging Element With Restricted Area Overflow Hidden

This scenario involves dragging a wider element than its parent, which has the CSS property overflow set to hidden. The parent's width and overflow settings are fixed and cannot be altered.

Below is the HTML code:

<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</div>

Here is the corresponding CSS code:

.container {
  position:relative;
  width:300px;
  height:50px;
  background:#ccc;
  overflow:hidden; // caution: changing to overflow-x:hidden will not work
}
.text {
  position:absolute;
  top:7px;
  margin:0;
  width:1000px;
  font-size:30px;
}

Incorporate jQuery like this:

$('.text').draggable({
  axis: 'x',
})

To enhance the demo, visit: https://jsfiddle.net/jeafgilbert/LtkkzccL/

The task at hand is to allow users to drag only the sentence without creating spaces before or after it.

Answer №1

To ensure a draggable element stays within bounds, you can monitor its position in the drag callback and adjust it accordingly.

In simple terms, if the left position exceeds 0, reset it to 0 to prevent it from going beyond that point. Similarly, if the difference between the draggable element's width and its parent's width is less than the left position, reset the left position to keep it within bounds.

Check out an updated example here

$('.text').draggable({
  axis: 'x',
  drag: function(event, ui) {
    var left = ui.position.left,
        offsetWidth = ($(this).width() - $(this).parent().width()) * -1;

    if (left > 0) {
      ui.position.left = 0;
    }
    if (offsetWidth > left) {
      ui.position.left = offsetWidth;
    }
  }
});
.container {
  position: relative;
  width: 300px;
  height: 50px;
  background: #ccc;
  overflow: hidden;
}
.text {
  position: absolute;
  top: 7px;
  margin: 0;
  white-space: nowrap;
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</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

How can I apply a custom class in Angular 2, similar to jQuery's

I've been having trouble with a very basic task... I need to assign a class to a <div> when I click on a button. After hours of searching online, I still haven't found a simple solution and all the examples I come across are too complex for ...

Dividing the code into a function and invoking it does not produce the desired outcome

Everything seemed to be working perfectly until I attempted to encapsulate the code into a function and call it within my expression. Unfortunately, this approach did not yield the desired results. Functional code: render: function() { return ( ...

What could be causing the space between float and div elements?

Could someone shed light on the reason behind the minor gap between the top navigation element and the content div underneath it in this jsfiddle? When I float the navigation list items, a slight gap appears between the top navigation element and the main ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Compare the values in the table before sending the email

After attempting to execute this particular script, I am encountering an issue where no emails are being sent to the user's email address. The functionality of the script involves comparing values in a specific column in a sheet (column 10) and sendin ...

Ways to ensure a div stretches all the way down to the bottom of the

div { background-color: #bada55; width: 475px; float: left; margin-left: 30px; height: 100%; } html, body { height: 100%; min-height: 100%; } <div> </div> I am facing an issue with extending a div to the bottom of the screen. De ...

Extract the JSON information and determine the frequency of each data item

I am looking to extract the json data and retrieve the count for Leadstage. Specifically, I aim to obtain the leadstage count based on geographical location. { "Geo" :"US East" "LeadStage": "SGL", &quo ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

Double Triggering Problem Arises During Partial Refresh

My dojo button bar is connected to a csjs function that performs a partialrefreshget() on a datable control. The datasource for the datatable control is a view. Within the this.keys property, I have implemented logic to check if the partialrefresh was ini ...

What is the best way to efficiently load all of my web applications within the web application that I am currently developing?

https://i.stack.imgur.com/IAjIW.png Greetings! I am currently a novice Web Developer and here is my current situation: I am working on developing 3 web applications, with one additional application that will load all three of them. Please refer to the im ...

Is it possible for a CSS code to be universally effective across all PHP files by setting style.css in header.php and then including header.php in each of the other PHP files?

Let me confirm, the code snippet from the header.php file is as follows: <link rel="stylesheet" href="style.css"> If I include the following code in every other php file: include 'header.php'; Will all the files have access to style.css ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...

Adjust tool tip text on the fly

As a beginner, I created a test table and now I want to make the tool tip text change dynamically when I hover over the table with my mouse. Ideally, I would like the tool tip text to correspond to the content of the table cell. Currently, I only have stat ...

How to retrieve values from a nested array in a Next.js application

I am diving into the world of nextjs and apollo for the first time, and I am currently facing a challenge with using .map to loop through database results. Below is the code for my component: import { gql, useQuery } from "@apollo/client" import ...

How to arrange DIVs and expand containers?

Is there a way to position a common div at the bottom of the page without forcing it out of its container, without specifying the container's height, and without setting its position to absolute? I want to place a div (alpha) at the bottom of the pag ...

The challenge of handling success and error messages in Ajax with HTML

I encountered an issue with this concrete problem. My goal is to dynamically display a message within a specific div based on the response from my ajax request. I have set up two divs with IDs #uploadResponsesuccess and #uploadResponseerror. However, since ...

Can a JavaScript function be classified as a "function", an "object", or perhaps even both?

I'm attempting to wrap my mind around the behavior of Javascript functions. Are they considered a function, an object, or possibly both at the same time? ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...

Guide to retrieve Player duration, current timestamp, and video frames or Seek Position using JQuery

I have successfully managed to put together this code that retrieves player duration, current time, and calculates a value used to update the progress bar width. For Example var slideOff = Math.floor((100 / totalTime) * currentTime); progBar.css({width ...

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...