Using jQuery to animate the width of a container after it is fixed to the top of the page based on the position of the

Wow, I've been tinkering away for hours and can't seem to crack this code puzzle.

Let's dive into some CSS:

#wrapper {
    margin: 0 auto;
    padding: 0 20px;
    width: 960px;
}

#wrapper .block {
    width: 920px;
    height: 690px;
}

#wrapper .container {
    background-color: #000;
    width: 920px;
    height: 80px;
}

#wrapper .container div {
    margin: 20px auto 0;
    width: 510px;
    height: 35px;
}

Seems pretty straightforward. We have a container nested within a block inside a wrapper. When the user scrolls past a certain point on the page, I want the container to stick to the top of the page and expand to the full width of the window. Likewise, it should revert back to its original state when scrolling in the opposite direction.

I've managed to make the fixation work using jQuery:

$(function() {
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 690) $('.container').css({
            'position' : 'fixed',
            'top' : '0',
            'left' : '50%',
            'margin-left' : '-460px'
        });
        if ($(this).scrollTop() < 690) $('.container').removeAttr('style');
    });
});

However, I'm struggling to figure out how to smoothly expand and retract the width of the container while keeping everything centered with no glitches or delays. The desired effect is for the container to gradually widen from its original width to fill the window after the scroll position reaches or exceeds 690px, and then shrink back before that point.

Here's my basic understanding:

$(function() {
    $('window').scroll(function() {
        if ($(this).scrollTop() >= 690) $('.container').animate({'width' : '100%'});
        if ($(this).scrollTop() < 690) $('.container').animate({'width' : '920px'});
    });
});

The challenge lies in integrating these two concepts seamlessly. I considered using a hidden div behind the container that animates once the scroll conditions are met, but that approach isn't yielding results either.

To help visualize, here's a representation of what I'm aiming for:

Do I need to tweak my CSS or jQuery, or both? Should I abandon ship and explore CSS3 transitions as an alternative? Or would that only complicate things further? It's driving me crazy that something seemingly simple is proving so elusive, and I'll lose my mind if there's a ridiculously easy solution I've overlooked, haha.

Any guidance or feedback would be greatly appreciated. Thank you!

Update

Some HTML:

<div id="wrapper">
    <div class="block">Some content</div>
    <div class="container">
        <div>A few navigation links</div>
    </div>
    <div class="main">Main content</div>
</div>

(P.S. - I know the semantics are messy, haha. This is all experimental. Thanks.)

Answer №1

Make sure to add parentheses to the .scrollTop() method.

It's not entirely clear what the expected results of applying the css are.

$(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() >= 300) {
          $(".container")
           .stop(true)
           .css("position", "fixed")
            .animate({
              "top": "0",
              "left": "50%",
              "margin-left": "-460px"
          }, 100);
        };
        if ($(this).scrollTop() < 300) {
          $(".container").stop(true)
            .css({
              "position": "relative",
              "margin-left": "0px",
              "left": "0"
          });
        };
    });
});
#wrapper {
    background-color: #ddd;
    margin: 0 auto;
    padding: 0 20px;
    width: 960px;
}
#wrapper .block {
    background-color: #aaa;
    width: 920px;
    height: 300px;
    display: inline-block;
}
#wrapper .container {
    background-color: #000;
    width: 920px;
    height: 80px;
    display: inline-block;
}
#wrapper .container div {
    background-color: #444;
    margin: 20px auto 0;
    width: 510px;
    height: 35px;
    transition: all 100ms ease;
}
#wrapper .main {
    background-color: #eee;
    width: 920px;
    height: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="wrapper">
    <div class="block">Some content</div>
    <div class="container">
        <div>A few navigation links</div>
    </div>
    <div class="main">Main content</div>
</div>

Check out the jsfiddle here: http://jsfiddle.net/eby5ygLy/2/

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

Deactivate chart settings in Highstock for smaller displays

We are facing a situation where we need to display highstock charts with real-time data on a page, but for mobile or smaller screens, we want to disable the navigator, zoom, and date range features and only show a basic highchart. Despite attempting to use ...

Is it possible to create this layout using Bootstrap 5? I want to stack spans, with one inside the container and one outside

Trying to achieve a specific design using Bootstrap 5.3. https://i.sstatic.net/STifm.jpg This design should be placed over the showcase, with the following code for the showcase displayed below: <div class="showcase d-flex flex-column"&g ...

Collecting Information from the DOM to Append to an Array with JavaScript

My aim is to create a fully functional shopping cart using either vanilla JavaScript or jQuery. I'm uncertain if I'm approaching it the right way, but here's my plan: Firstly, I want to establish an array named cartItems to store all sho ...

Performing an AJAX call using jQuery within a PhoneGap application to communicate with a Node JS server

I've searched everywhere online for a practical demonstration of a jQuery AJAX call to a Node JS server, but to no avail. Typically, a jQuery AJAX request to a PHP server follows this format: $("button").click(function() { $.ajax({url: "http://w ...

Is there a way to achieve the same zooming and panning effects on an element using CSS transform instead of jQuery's

If you click on the following link, you will see a jsFiddle that I have created to demonstrate my question: http://jsfiddle.net/VbCcA/3/ In my project, I have developed a function that allows for panning and zooming to a specific element. This function i ...

Display a tooltip when you click on a different element

I have a unique feature that I want to implement on my website. The idea is to display a tooltip when a user clicks on a specific div with the same ID as the tooltip. This will be particularly useful for interactive questions where users can click and reve ...

Background images are not transitioning to alternative images on mobile devices

I've been experimenting with my portfolio site (have a look at www.imkev.in) and I'm facing some issues on the mobile version. Despite having media queries in my CSS that should trigger a switch to smaller file sizes and differently cropped image ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

Checking for the Presence of a Word in a String Using jQuery

I'm currently developing an application that allows users to click on usernames to add them to a reply list. The issue I am facing is that if a user with a similar username is already added, the system mistakenly identifies the new username as already ...

Bootstrap Carousel with descriptions in a separate container without any display or hiding transitions

I have created a slider using Bootstrap and some JavaScript code that I modified from various sources. Everything is working well, but I want to remove the transition or animation that occurs when the caption changes. Currently, the captions seem to slide ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

Utilizing the scrollTop method to display the number of pixels scrolled on

My goal is to show the number of pixels a user has scrolled on my website using the scrollTop method in jQuery. I want this number of pixels to be displayed within a 'pixels' class. Therefore, I plan to have <p><span class="pixels"> ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Interacting with dynamically created input fields using Jquery from a JSON loop

I'm stuck trying to figure out why this code isn't working for me. I'm attempting to retrieve the value of a textfield that was generated via a loop from a JSON file. At the end of this code, I've added a simple click(function() {alert ...

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

EffortlessDrop.js and anchors

Currently using EasyDropDown.js to style a select element, which creates a modern dropdown menu using jQuery. I'm curious if it's possible to include a hyperlink in one of the select options. Here's an example of what I'm trying to ach ...

confused by the lack of guidance on manipulating arrays within the Autocomplete widget using Ajax

I am trying to work with an Autocomplete feature using geonames.org cities in the source option, but I'm facing some challenges when it comes to manipulating the arrays in the results. Despite having a test version that's "hard coded" and working ...

Is it possible to utilize $.getJSON() with a machine on the identical subdomain?

My server is called mybox.ourcorp.ourdomain.com. I am attempting to make a JSON request from this server to another server within the same subdomain, specifically http://otherbox.ourcorp.ourdomain.com/feed. When I manually enter this URL in a browser on m ...

Unable to identify modified identifier

After changing the id of a button, I am unable to detect the new id using .on("click"). Although console.log() does acknowledge the change, the on() function fails to detect it. Here is the HTML code: <form id="formName" action="" method="post"> ...