Automatically scroll a div when the internal div is in focus

I want to create a scrollable div that allows for scrolling even when the mouse is over the content inside the div, not just on the blank areas beside it. Here is the code I am currently using:

var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight - main.offsetHeight;

main.parentNode.parentNode.onscroll = function() {
   main.style.top = Math.min(this.scrollTop, maxTop) + "px";
}

It works fine in Chrome and IE8+ with a hack, but in Safari, the content shakes a lot when scrolling. Is there a way to fix this issue?

View a working example here: https://jsfiddle.net/8oj0sge4/6/

var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight - main.offsetHeight;

main.parentNode.parentNode.onscroll = function() {
  main.style.top = Math.min(this.scrollTop, maxTop) + "px";
}
#wrapper {
  width: 100%;
  height: 1500px;
  border: 1px solid red;
  padding-top: 380px;
}
#wrapper .container {
  border: 1px solid green;
  width: 100%;
  height: 500px;
  overflow: scroll;
}
#wrapper .container-scroll {
  height: 1500px;
  width: 100%;
  border: 1px solid yellow;
  position: relative;
}
#wrapper .main {
  width: 200px;
  height: 500px;
  background: black;
  overflow: scroll;
  position: absolute;
  color: white;
  left: 50%;
  margin-left: -100px;
  margin-top: 10px;
}
<div id="wrapper">
  <div class="container">
    <div class="container-scroll">
      <div id="main-site" class="main">
        My goal is to make the div container scroll even when the mouse hovers over this div in Safari. I already know how to make it work in Google and IE8, but Safari is shaking a lot!
      </div>
    </div>
  </div>
</div>

Thank you for any help.

Answer №1

Utilize this demo to enable scrolling of div content on mouse hover and reverting back when the mouse is moved out of the div.

<html>
</head>
<style>
.mydiv
{height: 50px;width: 100px; overflow-y: scroll; }
</style>

<script>
function loadpage()
{ document.getElementById('marquee1').stop();  }
function marqueenow()
{ document.getElementById('marquee1').start(); }
</script>

</head>
<body onload="loadpage()">
<marquee id="marquee1" class="mydiv" onmouseover="marqueenow()"     onmouseout="loadpage()" behavior="scroll" direction="up" scrollamount="10">
This is my test content This is my test content This is my test content This     is my test content This is my test content This is my test content This is my     test 

content This is my test content This is my test content This is my test     content This is my test content This is my test content This is my test content     This is my test content This is my test content This is my test content 
</marquee>
</body>
</html>

Answer №3

Uncertain about your intentions, but you can achieve a fixed position using CSS "fixed". This will keep the element in place wherever you position it. The following CSS code will fix the element to the bottom of the page.

.fixed {
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: auto;
}

If you need information on retrieving scrollbar position using Javascript, this answer may help: How to get scrollbar position with Javascript?

Answer №4

The importance of content selection is uncertain to me. Does it really need to be selectable?

If not necessary, a viable solution could involve utilizing

#wrapper .main{ pointer-events: none; }
. This would prevent the content from receiving any mouse events, allowing them to pass through to the element located behind it - in this scenario, the scroll would directly affect #wrapper.

Answer №5

The reason Safari behaves this way is due to the unique scrolling mechanisms that each browser employs. When a website has a fixed header, Safari displays a bouncy effect when scrolling on a phone, while on a PC it behaves more smoothly. In comparison, Internet Explorer scrolls seamlessly, while Chrome jumps directly to the desired location without a gradual transition.

Answer №6

The reason behind the constant movement of your #main-site is due to the browser continuously updating the position of this specific element.

A useful solution to address this issue is by employing a technique known as the Debounce Function. This approach involves delaying the execution of the scroll event handler in order to eliminate any pending callbacks.

For your circumstance, you can implement the following code snippet:

main.parentNode.parentNode.onscroll = function(event) {
    debounce(offsetting, 10);
}

function offsetting() {
    main.style.top = Math.min(main.parentNode.parentNode.scrollTop, maxTop) + "px";       
}

function debounce(method, delay) {
    clearTimeout(method._tId);
    method._tId = setTimeout(function(){
        method();
    }, delay);
}

If the jittering issue persists, you have the flexibility to adjust the delay parameter (e.g., revise 10 to 50). However, be aware that this may result in a temporary cutoff effect on your #main-site element, depending on the chosen delay settings.

Answer №7

It seems like your code is running smoothly on Chrome and IE, but there could be a potential issue with the scrollHeight or offsetHeight attribute when it comes to Safari. I suggest utilizing the getBoundingClientRect method for determining the position of elements, as it is known to be more dependable and precise.

var maxTop = main.parentNode.getBoundingClientRect().height - main.getBoundingCLientRect().height;

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

The function .classList.remove() is effective when applied to one element, but fails to work on a different element

I am facing an issue where only one element is getting affected when trying to remove classes from multiple elements if certain email input requirements are met. Can someone help me understand why this is happening? Here is the code snippet: const emailI ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Display an array comprising of other arrays

function PersonXYZ(fName, lName) { this.lastName = lName; this.firstName = fName; this.grades = []; this.grades.push([4, 67, 5]); this.grades.push([41, 63, 5]); this.grades.push([4, 67, 55]); } var person = new PersonXYZ('John', 'Doe&apos ...

Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly. I at ...

Send the DOM element to a processing function within AngularJS

In this code snippet, there is an attempt to pass a table cell (as a DOM object) to a function. However, it seems that the reference of 'this' does not point to the DOM object for the table cell, but rather to '$scope'. Any suggestions ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

Showing a variety of pictures within a specified time frame

In my CSS, I have defined classes that allow me to display different background images on a page at set intervals: .image-fader { width: 300px; height: 300px; } .image-fader img { position: absolute; top: 0px; left: 0px; animation-name: imagefade; ...

Tips for tailoring content based on screen size

I am looking for a way to display different content depending on whether the user is viewing my website on a large screen (PC/tablet) or a small screen (mobile). While my site is responsive and uses bootstrap, I have a lot of content that is only suitable ...

Is there a way to imitate a method that initiates an AJAX request?

I am currently working on writing tests for my Angular application and I need to mock a method in order to avoid making actual requests to the server. Within my grid.service.ts file, here is the method I am trying to mock: loadAccountListPromise(id: str ...

Tips for concealing boostrap spinners

Within the main component, I have an @Input() alkatreszList$!: Observable<any[]>; that gets passed into the child component input as @Input() item: any; using the item object: <div class="container-fluid"> <div class="row ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

The Jquery Load() function is causing [object object] to be returned instead of the element ID value when retrieving it

I am pulling a value from a MySQL query result in page.php and displaying it in display.html. I am successfully showing the value "VALUE368" in the div ID on display.html. However, I also want to log "VALUE386" in the Firebase Realtime Database. I am attem ...

Develop a custom JavaScript code block in Selenium WebDriver using Java

Recently, I came across a JavaScript code snippet that I executed in the Chrome console to calculate the sum of values in a specific column of a web table: var iRow = document.getElementById("DataTable").rows.length var sum = 0 var column = 5 for (i=1; i& ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

Does Typescript not provide typecasting for webviews?

Typescript in my project does not recognize webviews. An example is: const webview = <webview> document.getElementById("foo"); An error is thrown saying "cannot find name 'webview'". How can I fix this issue? It works fine with just javas ...

Guide to utilizing element reference with material UI components in Angular

I am facing difficulty in accessing the reference of an element. My intention is to wrap the material UI elements within a div and set the opacity: 0 so that it remains hidden in the HTML, allowing me to handle the value in my component.ts file. The main g ...

Eliminating gaps between elements

I recently delved into the world of web design, and although I have a basic understanding of HTML and CSS, I am determined to enhance my skills and knowledge by creating a standard home page. So far, I managed to create a standard navigation bar, and now ...