Changing the size of the logo as you scroll through the page

I have implemented the following code to resize the logo as I scroll down the page.

$(document).on('scroll', function() {
  if ($(document).scrollTop() >= 10) {
    $('.logo img').css('width', '50px');
  } else {
    $('.logo img').css('width', '');
  }
});
.nav {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
}

.nav .logo {
  position: fixed;
  text-align: left;
  z-index: 2;
  top: 0;
  overflow: hidden;
  opacity: .5;
}

.container {
  padding-top: 120px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <div class="logo">
    <a href="index.html"><img src="http://placehold.it/100x100" alt="" /></a>
  </div>
</div>
<div class="container">
  Lorem ipsum
</div>

I am looking for a way to make the transition smoother when resizing from large to small.

https://jsfiddle.net/sL89qxcx/

Is there any additional code that can be added to achieve a smooth transition?

Answer №1

To enhance the effect, consider utilizing CSS transitions which are hardware accelerated and promote a better separation of concerns. Control the animation by toggling a class in JavaScript.

Make sure to include both width and transition properties in the default state of the .logo img element. Modify the width value in the added class. See example below:

$(document).on('scroll', function() {
  $('.logo img').toggleClass('small', $(document).scrollTop() >= 10);
});
.nav {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
}

.nav .logo {
  position: fixed;
  text-align: left;
  z-index: 2;
  top: 0;
  overflow: hidden;
  opacity: .5;
}

.nav .logo img {
  width: 100px;
  transition: width 0.3s;
}

.nav .logo img.small {
  width: 50px;
}

.container {
  padding-top: 120px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <div class="logo">
    <a href="index.html"><img src="http://placehold.it/100x100" alt="" /></a>
  </div>
</div>
<div class="container">
  Lorem ipsum
</div>

Answer №2

Here are some helpful suggestions:

Try to avoid directly setting styles with the .css() method as a general practice (with exceptions, of course). Instead, consider defining a CSS class like .small-logo {width:8%}, and then add it using .addClass().

By doing this, you ensure that the class is only added once, preventing duplicate additions.

Furthermore, you can apply transitions like

transition: width 0.4s ease-in-out;
to your logo's styles for a smoother visual effect.

Embrace the creativity and enjoy working with CSS!

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

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

Error: The internal modules of node.js encountered an issue while loading causing an error to be thrown at

After installing Node.js (LTS version) from their website on my Windows system, I created a new directory named "mynode" and placed a text file inside it called "hellonode.js". Upon trying to run node hellonode.js in the command prompt after changing direc ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

Saving user-generated inputs within a React.js component's state, focusing on securely handling passwords

Curious about forms in React.js? I don't have any issues, but I'm wondering if there are potential flaws in my approach. I've set up a basic form with two inputs for email and password: <input type="email" name="email" value= ...

An error occurred while trying to retrieve the message from the JSON data in PHP/AJ

i have created a form in a PHP file and I am sending a request to another PHP file (test2.php) using AJAX. However, when I receive the data back in AJAX and try to print it in id="txtHint2" (paragraph tag), it shows as undefined. What could be causing th ...

Unable to make getJSON function properly with CodeIgniter

I'm experimenting with using getJSON to retrieve the most recent data from my database. So far, I've stored it in an array and used json_encode(the array). This method successfully displays the information on the view, but the problem lies in the ...

Problems with select tag change events

I encountered an issue with select tag onChange events. When I select a value from the select tag, it should display in a textbox that is declared in the script. It works perfectly when I remove the class "input" from the select tag, but I prefer not to re ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

Is it possible to execute a program on MacOS through a local HTML website?

Are there any straightforward methods to launch Mac programs using HTML? I've created an HTML page featuring a text field and several buttons. The goal is for users to enter a code (numbers) that will then be copied to the clipboard. By clicking on t ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

The NodeJS req.query is providing inaccurate information

When I send a JSON from the Client-Side to a NodeJS Server, it looks like this: $.ajax({ type: "POST", dataType: "jsonp", url: "www.xyz.com/save", data: { designation: "Software Developer", skills: [ "", "ASP.NET", "P ...

having issues with my expressjs router functionality

Embarking on my MEAN stack journey, I have been immersing myself in tutorials. It has become clear that everyone does not approach the logic in the same way. However, I find myself stuck on two particular examples. Example One: // server.js var express = ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

What are some strategies for creating a smooth transition with a max-height of 0 for a single-line div?

I have a div that is one "line" in height. When a button is clicked, I want it to disappear and simultaneously another div with more lines should appear. I have managed to make this work, but no matter what I do, the one-line div disappears very quickly al ...

Seeking advice on a coding dilemma: What is the best way to enable users to click on each item in a list they submit

Hey there, I'm no expert in this field so I could really use some help with my PHP document. Here's the situation: I have a PHP document that includes a form. Every time a user submits text into the input field, the text is echoed as a list item ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...