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

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results": [{ "name": "Bananas, r ...

Uploading images dynamically using Ajax and PHP upon submission

Currently, I am working on a modal that submits information and an image through a form to a database using PHP and JavaScript. However, my expertise in JavaScript is limited, so I could use some assistance. So far, I have successfully inserted data from ...

The strategy of magnifying and shrinking graphs on Google Finance for better analysis and

I am seeking to understand the logic behind a zoom-able graph similar to the one on Google Finance. I am aware that there are pre-made components available, but I am interested in a simple example that breaks down the underlying logic. ...

The functionality of a generated button has been compromised

My goal is to create a webshop that doesn't rely on MySQL or any database, but instead reads items from JSON and stores them in LocalStorage. However, I've encountered an issue where the functionality of buttons gets lost after using AJAX to gene ...

Troubleshoot: Unable to Change CSS on Click Using Javascript/jQuery

Having trouble creating three different buttons that toggle between various images using the CSS display property? Check out my code on https://jsfiddle.net/agt559e8/. function USradarChange1() { //document.getElementById("usradar1").src="weather/curr ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

What steps can I take to ensure that my bot disregards any actions taken by other bots?

I need assistance with configuring my bot to ignore certain actions by other bots and prevent logging them. Below is the snippet of my code: let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel); if (!messagecha ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

What could be the reason for the failure of this GET route in the jest test?

Currently, I am studying TDD and have crafted this test script: it("should call TodoModel.findById", async () =>{ await TodoController.getTodoById(req,res,next) req.params.todoId = "5f1216dd46a9c73dd812be36" e ...

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

transferring data to Amazon Web Services using Angular framework

I'm currently facing an issue while trying to send a file to an AWS server using an Angular dropzone. I have my AWS credentials ready, but I am unsure of how to properly make the request. Every time I attempt to drop the file into the dropzone, I kee ...

Node.js assert causes mocha to hang or timeout instead of throwing an error when using assert(false)

I am facing an issue with a mocha test that I have written: describe 'sabah', → beforeEach → @sabahStrategy = _.filter(@strats, { name: 'sabah2' })[0] .strat it 'article list should be populated&ap ...

Running Protractor tests can be frustratingly sluggish and frequently result in timeouts

After spending most of the afternoon struggling with this test, I've tried different approaches but none seem to work. The task at hand is searching for users within the company, generating a table, and selecting the user that matches the name. Curren ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Having trouble with installing node-steam on your node.js server?

I recently attempted to install node-steam and encountered a significant error. Can anyone provide guidance on how to resolve this issue? Is the mistake on my end? ... gyp ERR! configure error gyp ERR! stack Error: Can't find Python ex ...

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...