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

Loop through a collection of items based on the values in a separate array using jQuery

I have a list of objects below The newlist and SelectID array are both dynamic. I am populating through a function, now I need to iterate and create the new list. var newList = [ { id : 1,name="tea",plant:"darjeeling"}, { id : 2,name="cof ...

The image source is visible in Vue.js, but unfortunately, my picture is not showing up

Below is the code and script that I have: <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> ...

Using Javascript to prevent css from changing the display

I want to make some CSS adjustments to a single element using a single script, but I want all the changes to be displayed at once. For example: $("#someelement").css({width:"100%"}); //this change should not be displayed $("#someelement").width($("#someel ...

Center user input within a div element

I am trying to achieve proper alignment of input elements within a div. When the div is clicked, the input should be displayed; otherwise, a span should be shown instead. Here is my code: <!doctype html> <html lang="en"> <head&g ...

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { ...

Listener for body keystrokes

Is there a way to trigger a function when the space bar is pressed on the page, without it being called if an input field is focused? Any thoughts or suggestions? The current code triggers the function even when an input bar is focused: $(document).keydo ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Tips to prevent the @click event from firing on a specific child component

When I click on any v-card, it redirects me to a different link. However, if I click on the title "World of the Day", I don't want anything to happen. How can I prevent being redirected when clicking on the title? template> <v-card clas ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

Try refreshing the webpage if the AJAX Update Panel experiences an issue

Currently, my website displays the status of multiple servers and provides information about user numbers in various systems. I have set up an AJAX UpdatePanel with an asp:Timer control to automatically refresh the data. Although this setup works smoothly ...

Encountering a constructor problem while Jest is mocking a class from an NPM module

I'm currently attempting to create a mock for the Discord.JS module. Within this module, there is a Client class that I am extending in my own "Bot" class. My goal is to mock the module in order to simulate certain methods on other classes such as "Me ...

Getting the Kendo UI AutoComplete value onKeyUp within a ViewModel: A step-by-step guide

I'm facing an issue with the Kendo UI AutoComplete. I need to capture the value as the user types in order to send a query to the server for result filtering. The change event only triggers onBlur and not on keyup/down/press events. Additionally, the ...

Utilizing Ajax and Jquery within Zend framework

I'm working with the Zend framework using PHP and attempting to submit a form via ajax/jquery. Below is the structure of the .phtml file: <form id="find"> <input type="text" name="name"> <input type="submit" id="submit" value ...

Presenting data in various formats

I've got a JSON file with a list of data that includes months and years. I want to display all the months, but have the year only appear once in a big block area. Here's an image example: https://i.stack.imgur.com/Ps3OF.png The image demonstrates ...

Circular CSS menu

What I'm Trying to Achieve: I am interested in developing a unique radial menu that includes interactive elements, such as the central image and the surrounding sections. It is imperative that the solution is compatible across all browsers. The examp ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

Prop type failure: The `actions` prop is specified as mandatory in the `Testing` component, however, its value is currently undefined

I am working on a project that involves creating a login form using React and Redux. Here's a snippet of my app.js: import React from 'react'; import { render } from 'react-dom'; import Input from 'react-toolbox/lib/input&apo ...

Prevent users from navigating back in their browser with jQuery

As I work on developing an online testing app, one of the requirements is to prevent users from refreshing the page or going back during the test until it has ended. While I have successfully disabled the refresh action in jQuery using various methods with ...

Develop a DIV element that remains constant throughout different web pages without having to reload

How can I create a non-reloading div at the top of my website that contains an MP3 player which plays continuously while users browse through the site? I am working with Joomla and would like to avoid using Iframes for search engine optimization purposes ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...