What is the relationship between JavaScript and the height of a window?

Consider the code snippet below:

 24 <script type="text/javascript">
 25 
 26 function UpdateDisplay($isVisible){
 27         if($isVisible)
 28                 $('.relatedContent').stop().css({
 29                         "transform": "translate3d(-20px,0,0)"
 30                 });
 31         else
 32                 $('.relatedContent').stop().css({
 33                         "transform": "translate3d(105%,0,0)"
 34                 });
 35 }
 36 
 37 $(document).ready(function(){
 38         var offset = $(window).height() / 9;
 39         
 40         if($('body').height() > ($(window).height() + offset))
 41                 $(window).scroll(function( e ) {
 42                         
 43                                 if($(window).scrollTop() > offset)
 44                                         UpdateDisplay(true);
 45                                 else
 46                                         UpdateDisplay(false);
 47                 });
 48         else
 49                 UpdateDisplay(true);
 50 });
 51 
 52 </script>

This script triggers a pop-up element on a website upon scrolling.

You mentioned wanting to delay the appearance of the item until later in the scroll, such as when reaching a specific distance like 100 pixels from the bottom of the page.

Changing the value at line 38 doesn't yield any visible changes. How can this effect be achieved?

Answer №1

I made some improvements to your code.

Give this code snippet a try and read through the comments I included for clarity on the changes made. It functions quite well but may require a bit of adjustment in certain scenarios.

To test it out Simply scroll down until you encounter the pop up

function ToggleBlock($bShow) {
  // For smoother animations, Show and Hide can be used
  if ($bShow) {
    $('.nkRelBlock').show(1000);
  } else {
    $('.nkRelBlock').hide(400);
  }
}

$(document).ready(function() {
  // Set Half Body (divide by 2)
  var halfBody = $('body').height() / 2;
  // Find the maximum possible scroll from top
  var maxScrollTop = $('body')[0].scrollHeight - window.innerHeight;
  
  // Set on Scroll event
  $(window).scroll(function(e) {
    // Set common scroll factor which is the half body
    var scrollFactor = halfBody;

    if (halfBody - maxScrollTop > 0) {
      // In situations where the scroll is smaller than half the body e.g. when window and body height are relatively small..
      scrollFactor = halfBody -maxScrollTop;
    }
    if ($(window).scrollTop() > scrollFactor) {
      ToggleBlock(true);
    } else {
      ToggleBlock(false);
    }
  });
});
body {
height: 1000px;
}
.nkRelBlock {
margin-top: 0 !important;
position: fixed;
width:5vh;
height: 5vh;
background-color: red;
color: white;
font-weight: bold;
padding: 30px;
border-radius: 10px;
    /* Initially hidden */
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nkRelBlock">Hi!</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

What are the steps for implementing timezone-js?

I found a project on GitHub that claims to convert one timezone to another. I've been trying to get it to work without success. After downloading and extracting the files, I created an HTML file with the following code: <html xmlns="http://www.w3. ...

Is it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...

What sets Express.js apart from koa2.js in handling asynchronous functions?

I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code: router.get('/',(req,res)=>{ queries.getAll().then(stickers=>{ res.json(stickers) }) ...

Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked. Initially, I attempted to mock ...

Performing real-time arithmetic calculations on dynamic text input fields using AngularJS

In the process of creating a dynamic form, the number of textboxes is determined by the situation at hand. Each textbox is assigned an arithmetic formula, which is obtained from a database table. The structure of my form will be as follows: <div ng-ap ...

Attempting to utilize a for loop in JavaScript to condense code, however encountering a "not defined" error

I'm relatively new to working with javascript and currently attempting to enhance the following code snippet (which has been tested and is functioning correctly): // snail 1 // var s1 = document.createElement("div"); s1.id = snail1.id; s1.className = ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

Experiencing Chrome freezing issues due to a setInterval function in combination with React

Can anyone assist me with a countdown issue using React? I am trying to set the minutes and seconds by clicking on + and - buttons, then passing the seconds to a new variable called tottime. However, when the user clicks on Go!, the countdown should start ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Optimizing Window Width with React.js and CSS

I'm currently in the process of building a responsive website with react. I am utilizing CSS stylesheets for styling and have used @media queries to ensure responsiveness. However, I've encountered an issue while testing in Chrome where the elem ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

Is it possible to view JavaScript methods in the watch window of IE's debugger?

Can I view custom methods in the IE developer toolbar's watch window? For example, if I have a global function named hello, can I locate it within the DOM? function hello() { alert("hello"); } If so, where in the watch window would I find them? ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...

Sending a POST request in nodeJs that does not return any value

I have a button on my client site that sends a POST request to my server. The request does not require a response as it simply inserts data into the database. However, after clicking the button, the client continues to wait for a response until it times ou ...

Streamlined approach to triggering ng-change on a single textbox

Consider this array within an angular controller: somelist = [ { name: 'John', dirty: false }, { name: 'Max', dirty: false }, { name: 'Betty', dirty: false } ]; To iterat ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...