The function $(window).scrollTop(); does not trigger fast enough

I have been working on creating a header that shrinks as you scroll down, stopping at a certain point. The header also includes a logo that moves up with it.

However, I'm facing an issue where $(window).scrollTop(); doesn't respond quickly enough. If you scroll too fast, the logo may end up outside of the header or the header may be slightly oversized.

I'm struggling to find a better solution for this. Any help or ideas would be greatly appreciated.

Here is the code I currently have:

var widgets = {
    header: function() {
        var $header = $('.header');
        var $logo = $('.header__title');
        var $headerHeight = $header.height();
        $(window).on('scroll resize', function(event) {
            var windowWidth = window.innerWidth;
            var windowScrollTop = $(window).scrollTop();


            if( windowScrollTop < 100) {
                $logo.css('margin-top','-'+(windowScrollTop)+'px'); 
            }

            if ( windowScrollTop < 230) {   
                $header.css('height',($headerHeight - windowScrollTop)+'px');
            }
        });
    }
}

$(document).ready(function() {
    widgets.header();
    .....

You can see an example here: http://jsfiddle.net/7wp51gu6/

Answer №1

Make sure to set the final state within the else block for each condition.

if (windowScrollTop < 100) {
    $logo.css('margin-top', '-' + (windowScrollTop) + 'px');
} else {
     $logo.css('margin-top', '-100px');
}

if (windowScrollTop < 230) {
    $header.css('height', ($headerHeight - windowScrollTop) + 'px');
} else {
    $header.css('height', ($headerHeight - 230) + 'px');
}

View a demo at http://jsfiddle.net/gaby/7wp51gu6/7/

Answer №2

I just made some quick updates and would love to hear your thoughts on them. Check out this fiddle for a closer look...

http://jsfiddle.net/7wp51gu6/6/

The main change I made is in the script section:

if (windowScrollTop >= 100) {
    $logo.css('margin-top', '-100px');
}else{
    $logo.css('margin-top',0);
}

This code ensures that when the scroll position reaches or exceeds 100, the logo moves to its desired position. It also resets back to the original position when at the top.

In addition, I adjusted some CSS to move your primary content down by 312px. Take a look and see if it fits your needs. While not essential right now, it may be helpful based on your current layout.

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

Extracting the URL of the @font-face declaration in CSS with the use of JavaScript

Currently, my CSS file contains numerous @font-face tags. Each tag specifies a unique font-family and src URL. @font-face{ font-family: Garamond; src: url('ePrintFonts/pcl_91545.ttf'); } @font-face{ font-family: C ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

Swipe horizontally on mobile devices with text scrolling

I stumbled upon a workaround online that effectively allows for horizontal scrolling on mobile devices. <div style="max-width: 1024px; margin: auto; "> <ul style="white-space: nowrap; overflow-y: hidden; overflow-x: scroll; -webkit-overflow-sc ...

Ajax completes a request without receiving a response

Recently, I crafted an AJAX request that redirects the page once it's completed, without paying attention to the response it receives. My main goal is to ensure that the POST request is fully sent before triggering the redirect. Most of the informati ...

Retrieve JavaScript Variable Value when Button is Clicked via asp:HiddenField

Having limited experience with JavaScript and jQuery, I decided to make some modifications to a jQuery Slider for adjusting dates. You can check out what I've done so far here: http://jsfiddle.net/ryn_90/Tq7xK/6/. I managed to get the slider working ...

Exploring Browser History using Cascading Style Sheets

Currently, I am in need of researching a topic for my University project. Unfortunately, the internet has not provided me with any information on this specific subject. The task at hand is as follows: "How and under what circumstances can one uncover ...

"Authentic" foundation for typography

Line spacing in web design is different from line spacing in print design, such as in programs like InDesign. Here are the results: Web example: http://jsfiddle.net/Y9M28/4/ (works better in webkit) Print example: http://jsfiddle.net/Y9M28/3/ I have t ...

Using AJAX with Rails to add data to multiple items in a one-to-many association

In my Rails application, I have set up a one-to-many association where a Song has many Channels, and each Channel belongs to a Song. The challenge I am facing is when trying to create a new Song with 6 Channels. Below is a snippet of the form in the fronte ...

capable of concentrating but unable to enter text into input field using jquery

I have a set of five rows, each containing three columns of text boxes, along with a single text area. When tabbing from the third column in a row, the focus should shift to the text area, and then tabbing from the text area should move to the next row of ...

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

"Encountering a 404 error in a JQuery Ajax POST request when trying to send

Recently, I have been working with Adobe InDesign extensions and one of the tasks involves uploading an XML file to a server using a jQuery AJAX POST call. To achieve this, I need to read the XML file from the file system, store it in a variable, and then ...

Using AJAX and the Simple HTML DOM Parser to automatically fill in form fields

I'm currently working on a script that utilizes AJAX in combination with the Simple HTML DOM Parser to automate form filling. Here is what I have accomplished thus far: Check out my PHP file (discogs.php) below: <?php ini_set('user_agen ...

Ways to unveil a concealed div element using JavaScript

If javascript is disabled, I want to hide a div. If javascript is enabled, however, I don't want to rely on using the <noscript> tag due to issues in Chrome and Opera. Instead, my approach is as follows: <div id="box" style="display:none"> ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

Switch the class of the child element from the previous element using jQuery

I'm attempting to create a toggle effect on click that switches a class (font awesome) like this: $( ".expandTrigger" ).click(function() { $( ".expand" ).first().toggle( "fast", function() {}); if ( $( this ).prev().child().is( ".fa-plus-cir ...

Update the CSS dynamically using JavaScript or AngularJS

Is there a way to dynamically modify this CSS style using JavaScript or in an Angular framework? .ui-grid-row.ui-grid-row-selected > [ui-grid-row] > .ui-grid-cell{ background-color: transparent; color: #0a0; } .ui-grid-cell-focus ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

Organize your file dependencies efficiently using NPM

I'm currently part of a medium-sized team working on a large front-end application. Up until now, we have been using requirejs and AMD modules to manage our project with approximately 500 files. However, we recently decided to transition to commonjs a ...

Datatables - Array within an array

How can I access the 'emergencies' array in this case? {"organizationUuid":1,"emergencyUuids":null,"emergencies":[{"emergencyUuid":1,"emergencyTitle":"Student Fainted in Class","pickupLocation":"1122 Fowler St. 30309","possiblePatientUuids":[1, ...

Unusual issue with jQuery's AJAX functionality

Utilizing jQuery AJAX, I am fetching data from a PHP page and displaying a loading GIF image in the placeholder to indicate that results are being processed. $(".project").change(function(){ $(".custName").html("<img src='/admin/images ...