Stop the automatic scrolling feature in contenteditable areas

I am trying to figure out how to prevent my editable element from scrolling and repositioning when the cursor leaves its wrapper. Is there a way to fix this issue using only CSS without changing the structure of the elements?

.wrap {
  position: relative;
  border: 1px solid red;
  width: 70%;
  margin: 0 auto;
  overflow: hidden;
}

.wrap .item {
  position: absolute;
  white-space: nowrap;
  left: 70%;
  top: 50%;
  background: rgba(20, 20, 20, .5);
  color: white;
  padding: 10px 15px;
  display: inline-block;
}

img {
  width: 100%;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrap">
  <img src="http://placehold.it/350x150"/>
  <div class="item" contenteditable="true">Write HERE to get very long text and see scroll</div>
</div>

Answer №1

Take a look at my revised code below. The line will remain unbroken and the image will not be scrolled:

.wrap {
  position: relative;
  border: 1px solid red;
  width: 70%;
  margin: 0 auto;
  overflow: hidden;
}

.wrap .item {
  position: absolute;
  white-space: nowrap;
  left: 70%;
  top: 50%;
  background: rgba(20, 20, 20, .5);
  color: white;
  padding: 10px 15px;
  display: inline-block;
  right: 0;
  overflow: hidden;
}

img {
  width: 100%;
  display: block;
  position: sticky;
  top: 0; left: 0; right: 0; bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrap">
  <img src="http://placehold.it/350x150"/>
  <div class="item" contenteditable="true">Feel free to WRITE HERE to insert long text and observe scrolling effect</div>
</div>

Answer №2

This unique solution was inspired by the brilliant @Julian D. and his amazing hack. Although not flawless, it addresses the issue of weird flickering caused by opacity switching during certain points.

body {
  overflow: hidden;
}

.wrap {
  width: 70%;
  margin: 0 auto;
  overflow: hidden;
}

.wrap .item {
  position: absolute;
  white-space: nowrap;
  left: 70%;
  top: 50%;
  background: rgba(20, 20, 20, .5);
  color: white;
  padding: 10px 15px;
  display: inline-block;
  max-width: 60px;
}

img {
  width: 100%;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(function() {
    var editableElement = $('#editable'), clonedElement;

    // Revert any scrolling                    
    editableElement.on("scroll", function(event) {
      editableElement.scrollTop(0);

      // Try to prevent scrolling completely (doesn't seem to work)
      event.preventDefault();
      return false;
    });

    // Switch overflow visibility on and off again on each keystroke.
    // To avoid flickering, a cloned element is positioned below the input
    // and switched on while we hide the overflowing element.
    editableElement.on("keydown", function() {

      // Create a cloned input element below the original one
      if (!clonedElement) {
        var zIndex = editableElement.css('zIndex');
        if (isNaN(parseInt(zIndex, 10))) {
            zIndex = 10;
            editableElement.css({zIndex: zIndex});
        }    

        clonedElement = editableElement.clone();
        clonedElement.css({
            zIndex: zIndex-1,
            position: 'absolute',
            top: editableElement.offset().top,
            left: editableElement.offset().left,
            overflow: 'hidden',
            // Set pseudo focus highlighting for webkit
            // (needs to be adapted for other browsers)
            outline: 'auto 5px -webkit-focus-ring-color'
        });
        editableElement.before(clonedElement);
      } else {
        // Update contents of the cloned element from the original one
        clonedElement.html(editableElement.html());
      }

      // Here comes the hack:
      //   - set overflow visible but hide element via opactity.
      //   - show cloned element in the meantime
      clonedElement.css({opacity: 1});
      editableElement.css({overflow: 'visible', opacity: 0});

      // Immediately turn of overflow and show element again.
      setTimeout(function() {
        editableElement.css({overflow: 'hidden', opacity: 1});
        clonedElement.css({opacity: 0});
      }, 0);

    });
  });
</script>

<div class="wrap">
  <img src="http://placehold.it/350x150"/>
  <div id="editable" class="item" contenteditable="true">Write HERE to get very long text and see scroll</div>
</div>

Answer №3

To prevent scrolling, consider using position: fixed; instead of absolute

.wrap {
  position: relative;
  border: 1px solid red;
  width: 70%;
  margin: 0 auto;
  overflow: hidden;
}

.wrap .item {
  position: fixed;
  white-space: nowrap;
  left: 70%;
  top: 50%;
  background: rgba(20, 20, 20, .5);
  color: white;
  padding: 10px 15px;
  display: inline-block;
}

img {
  width: 100%;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrap">
  <img src="http://placehold.it/350x150"/>
  <div class="item" contenteditable="true">Enter text HERE to observe long scroll effect</div>
</div>

Answer №4

Specify the pixel value for the width of a contenteditable div.

.wrap {
  position: relative;
  border: 1px solid red;
  width: 70%;
  margin: 0 auto;
  overflow: hidden;
}

.wrap .item {
  position: absolute;
  white-space: nowrap;
  left: 70%;
  top: 50%;
  width:100px;
  background: rgba(20, 20, 20, .5);
  color: white;
  padding: 10px 15px;
  display: inline-block;
  overflow-x: auto;
}

img {
  width: 100%;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrap">
  <img src="http://placehold.it/350x150"/>
  <div class="item" contenteditable="true">Enter text HERE to create a long message and observe scrolling effect</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

I'm currently working on validating a registration form using the jqueryValidation engine plugin, and encountering issues with certain validations not functioning as expected

My experience with PHP is still new, and I'm currently exploring how to validate a signup form using the jqueryValidation engine plugin. While I managed to validate some aspects successfully, I've hit a roadblock with the user name validation par ...

How can I retrieve the class value of an element with multiple classes assigned using jQuery?

Is it possible to add or remove classes from an element that already has multiple classes assigned to it? Here is the HTML code in question: <div class="heading"> more html code here </div> I am interested in adding a class and then retrievi ...

Hide the navigation bar elements specifically on Safari browser when using Bootstrap v4.5.3

I'm having an issue with my Bootstrap v4.5.3 navbar not displaying correctly on Safari browser. All I see is the colored line, no text or hamburger icon. Can anyone help me with this? Here is my Navbar Code: <nav class="navbar navbar-expand-l ...

What is the best way to include a specific stylesheet for Blackberry Curve devices based on certain conditions

Is there a method to include a custom style-sheet specifically for the 'Blackberry curve 2007'? Or perhaps implement a redirect that can identify this device and direct them to a different .html page? I'm looking to create a simplified versi ...

Nested filtering using jQuery

My goal is to make the first 6 columns of a GridView trigger an action upon clicking, while also highlighting the entire row. Although I've successfully implemented row highlighting, I'm struggling with capturing the click event for the first 6 c ...

Adjust the parent <div> border based on the content of its two child <div> elements

I am having trouble getting a border to wrap around my <div> element that contains two child elements. Currently, the green border is only showing at the top of the container and not all around it. Can someone please provide guidance on how to resolv ...

What are the steps to change the layout of a horizontal navigation bar to vertical in WordPress?

During my journey of converting HTML to a WordPress theme, I encountered an issue with the navigation bar in the HTML code. Here is how it looks: https://i.sstatic.net/4giqL.png This is how the main HTML website appears: https://i.sstatic.net/K8LJ9.png ...

Animate an element to shift towards the lower left corner

My goal is to smoothly move a <p> element to the bottom left of the page using CSS animation. However, I'm encountering issues with the animation as it starts at the original place and abruptly ends at the bottom. I need the animation to be seam ...

Using jQuery to extract the initial 50 characters from a magnetic stripe reader input, analyzing the information, and smoothly moving to the next field to prevent any overflow

I am currently utilizing a magstripe reader for entering data into a text field. Specifically, I am interested in capturing only the first 50 characters. To achieve this, I have implemented an on.('input', function) event listener to monitor the ...

The React Navbar fails to appear when using React JS

I am currently in the process of creating a single-page website. I have incorporated react-bootstrap for the navigation bar, but I am facing an issue where it is not rendering on the page. Despite not encountering any errors, the page remains blank. Below ...

Modern design featuring soft borders that blend into the background

I am in the process of bringing a unique webpage layout to life. The design is a bit unconventional, and I'm not sure if it's feasible. Essentially, I plan to have a fixed-width content box of 900px positioned in the center of the page body. I ai ...

What is the best way to implement a live search feature using jQuery ajax for Django models?

After attempting to implement live search using jQuery and Ajax, as well as seeking help on the issue here, I have encountered a serious problem in my code. The search functionality works correctly and displays the content as expected. However, upon delet ...

Using jQuery to animate the expansion of a div downwards

I am trying to achieve a functionality where clicking on a table cell will cause another div element in a different table cell to collapse. $(function slideDown(id) { $("getdiv"+id).fadeIn(); }); The table row (hover function): <tr class="odd" id ...

hide input type with minimal display

Can someone help me find the less equivalent to this css code snippet? I'm not familiar with less and this code is part of a larger global css file that includes generated code from all less files. input[type="checkbox"] { display: none; } Any a ...

What are the steps to create a downpour in every location on Earth

Is there a way to create a continuous raining effect for my weather app using CSS only? I have achieved a satisfactory look, but the rain effects seem to only cover random chunks of the screen rather than the entire screen. How can I make it cover the enti ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Encountering a 404 Not Found issue while trying to add scripts with Node.js

I am currently working with a node server and an HTML file, where the default route is being directed. server.js /** * Created by Creative Coder on 10/26/2015. */ var express = require('express'); var mysql = require('mysql'); var a ...

Adjusting the CSS styling of my iframe element

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> $(document).ready( function () { $('#iView').load( function () { $('this').contents().find("html").css("background-image","none"); }); }); ...

Incorporating PHP code into HTML

I was wondering about the comparison between: <td><?=JText::_('_EMAIL')?></td> and: <td><?php echo JText::_('_EMAIL')?></td> I am aware that we can do: <td class=<?=$somestring;?>> &l ...

Using Django to run a function and display the output on a template without needing to refresh the page

Currently, I am using django to work on my website. On a specific page, there is an input 'x' which triggers a function when the enter key is pressed. Once this happens, the page refreshes and displays the result. But what I really want is for it ...