Shrink the width of a Div element when scrolling down, and expand it back to its original width when scrolling back to

Is there a way to decrease the width of my div element when I scroll down, and then increase it back up when the user scrolls back to the top (150 pixels or less)?

I attempted the code below which successfully reduces the width while scrolling down, but does not return to the original width when scrolling to the top.

I'm unsure of what I may be overlooking.


$(document).scroll(function() { 
    var scrollPosition = $(this).scrollTop();

    if (scrollPosition <= 150) {
        $("div.mydiv").animate({
            width : "20%"
        });
    }
    else {
        $("div.mydiv").animate({
            width : "50px"
        });
    }
});

Any suggestions on what I need to add or change?

Thank you

Answer №1

Consider this approach:

$(window).scroll(function() { 
var position = $(this).scrollTop();
if (position <= 150) {
if($("div.mydiv").is(":animated")){
}else{
$("div.mydiv").animate({
width : "20%"
},100);
}
} else {
if($("div.mydiv").is(":animated")){
}else{
$("div.mydiv").animate({
width : "50px"
},100);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv" style="width:20%;height:1500px;border:1px solid black">DIV TEST</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

The REST service is experiencing an issue where the server fails to acknowledge the get request sent by the client

(I appreciate your patience as I navigate my first post on Stackoverflow and potentially mess up the question formatting.) I am currently working on a project where my client needs to send a request to the server to retrieve information about a person with ...

Prevent scrolling within an iframe

I really need some assistance. Can anyone help me figure out how to disable scrolling in the iframe inside my div so that I can use the scroll of the div instead? I have tried using overflow:hidden and scrolling="no" but nothing seems to be working. Any s ...

Is there a way to hide my jQuery menu?

Can anyone help me figure out how to make it close when I click on a link? <nav class="navigation"> <a href="" class="menuIcon"><i class="fa fa-bars"></i></a> <ul class="nav"> <li class="clearfix"&g ...

PHP submitting form saves zeros

I have encountered an issue with submitting a form entry provided by the user. Instead of storing the actual values entered by the user, the database is recording 0 as the input. I require assistance to rectify this problem. Below is my code snippet: & ...

Beginner in html, css, and javascript: "Tips for saving jsfiddle demos?"

Recently, I developed an interest in JavaScript and CSS and came across some impressive examples on jsfiddle. I was wondering if there is a way to "export" these examples to my computer. Simply copying and pasting doesn't seem to work. How can I modi ...

When launching a modal window, the ability to dynamically change the URL and seamlessly transition into the modal window using Bootstrap 3, AngularJS, and CSS

Hello, I am looking to create a modal window that changes the URL when opened. For example, if a user clicks on a link with #123, the URL should change to include #123 after the slash. Additionally, I would like to be able to send someone a link directly ...

Customizing Bootstrap modal backdrop with CSS

I'm exploring how to achieve the backdrop effect of the Bootstrap modal without actually having to load a modal. However, I'm struggling to make it work correctly. Can anyone provide insight into the CSS that the Bootstrap backdrop utilizes inter ...

Using Regex named groups in JavaScript's replace() method

Currently in my JS project, I am facing a challenge while trying to create an object using the code snippet below. My difficulty lies in extracting regex named groups using the replace function provided. var formatters = { 'p': 'padding& ...

Retrieving extra data from JSON

Instead of just returning a success status in the JSON response from the controller, I would like to also include the person's name. Currently, the JSON response indicates whether the operation was successful and uses JsonRequestBehavior.AllowGet. T ...

How can we optimize performance in Three.js by controlling the frame rate with requestAnimationFrame?

When working on certain projects, I've found that 60fps may not be necessary. Instead, I thought about increasing the number of objects and elements running at 30fps to ensure smooth performance. One idea I had was to modify the requestAnimationFrame ...

Conceal top shadow with box shadow

I've been through about 10 questions on this topic and couldn't find a solution that fits my specific situation. Here's an example I created: http://jsfiddle.net/Y4uHm/4/ I'm trying to hide the shadow at the top of the content box. N ...

The September/October 2013 release of the Ajax Control Toolkit is causing conflicts with jQuery

After updating our project to utilize the latest October 2013 release of the Ajax Control Toolkit for the HTML editor extender and Ajax file uploader, we encountered unexpected issues. Our ASP.NET 4.0 project, which previously used C#, jQuery 1.9.0, jQuery ...

Guide to creating a unique link to contact a specific phone number through Telegram

Recently, I discovered a cool HTML trick that allows users to contact someone directly from a webpage using WhatsApp: <a href="https://api.whatsapp.com/send?phone={{phone_number}}" target="_blank">WhatsApp</a> Now, my curio ...

Issue with background color not showing up in blank cells of a table

I am working with a table that has alternating gray background colors for every second row. However, I'm having trouble capturing the empty cells. Even though I have applied CSS to target every even row, the empty cells are not being affected. Here is ...

How to position an image within a paragraph using HTML and CSS

I've been trying different CSS properties like 'vertical-align' but I'm still unable to align the image at the center of the paragraph HTML: <p><img id="imgPhone" src="phone.png">00244 913 513 199</p> CSS: img { ...

php event onchange onload selection

When setting up an HTML form with a select statement like this, <form method="post"> <select name="sortOrder" onchange="form.submit()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3 ...

Attempting to align one canvas with another causes the canvas to go haywire

Currently, I have two canvases set up in my game. The first canvas (rect1) moves randomly on the board while the second canvas (zombie) is supposed to follow rect1, but it seems to be moving all over the place instead of following correctly. Below is the c ...

Display a div using a PHP statement

I'm struggling to retrieve a specific div from my PHP function. Here is the code: error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); require_once("./include/membersite_config.php"); if (!$fgmembersite->Chec ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

Adding padding with and without child elements

As I work on styling a basic menu, I'm struggling to find a solution for adding padding to list items so they all have a consistent look. The challenge arises from the fact that I have an unordered list where list items may or may not contain an anch ...