Changing class in jQuery ignores CSS style

I have a id="header" div that initially has css rule: padding: 25px 0;. I want to decrease the padding of this div when scrolling down the page.

$(document).ready(function() {
  var headerID = $("#header");
  $(this).scroll(function() {
    if (!$(this).scrollTop()) 
      headerID.toggleClass("headerScrolled");
    else if (!headerID.is(".headerScrolled")) 
      headerID.toggleClass("headerScrolled");
  });
});
.headerScrolled {
  padding: 15px 0;
}

Despite implementing this code, I am not seeing any changes in padding while scrolling down. What could be possibly wrong with my code?

Answer №1

Your conditions are conflicting with each other, causing them to negate their effects. It would be more effective to simplify the logic by using a single call to toggleClass() and providing a boolean argument based on the current value of scrollTop to determine whether the class should be added or removed. Additionally, ensure that you are listening for the scroll event on the window rather than the document. Here is an updated approach:

$(document).ready(function() {
  var $header = $("#header");

  $(window).scroll(function() {
    $header.toggleClass('headerScrolled', $(this).scrollTop() !== 0);
  });
});
html,
body {
  height: 1000px;
  margin: 0;
}

#header {
  padding: 25px 0;
  background-color: #CCC;
  width: 100%;
  position: fixed;
}
#header.headerScrolled {
  padding: 15px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
  Header
</div>

Answer №2

Utilize the .scroll() method on the window element, rather than using this or the document. It might also be more convenient to employ the .addClass() and .removeClass() methods in this scenario.

$(document).ready(function() {

  var $header = $("#header");

  $(window).scroll(function() {
    if (!$(window).scrollTop()) {
      $header.addClass("headerScrolled");
    } else {
      $header.removeClass("headerScrolled");
    }
  });

});

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

Using Event Delegation in Practice

I am facing an issue with loading 2 <span> elements from separate ajax scripts onto a webpage upon selection from a dropdown box. Here is a snippet of my code: <span id='room_rate'>1,000</span> // content loaded by one ajax scri ...

Tips on maintaining the Parent menu in a hovered state when the mouse is over the child menu within a Dropdown Menu

I have been working on creating a dropdown menu that functions correctly. However, I am facing an issue where the top menu, when hovered, turns white, but as soon as I move down to the submenus, the top menu reverts back to its original color. Is there a ...

Incorporating functions from another JavaScript file within an AJAX request

There's a function called _HideErrorBox() in the file 1.js that I want to use in the file 2.js within an AJAX call. I'm loading both 1.js and 2.js in a specific order. Here's the content of 1.js: var Calculations = function() { var _H ...

Calling functions by name in Java using JSON objects

Is it possible to invoke a function from a Java JSON object? For example: In Java: JSONObject json = new JSONObject(); json.put("fnRowCallback", "test()"); Using jQuery: $ (function () { "use strict"; function test() { alert('test ...

Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section. <Collapse defaultActiveKey={["1"]} expandIconPosition="right" > <Panel header="This is p ...

Prevent an interruption in the flow of content by keeping the line unbroken

Having an issue with a visible line break between the content of an HTML element and its :after content. The problem arises in a sortable table where a small arrow is displayed at the top. To view the problem, check out this fiddle http://jsfiddle.net/ceu ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...

Circular images display corners during the transition before returning to their rounded shape

While working with Bootstrap 5.3, I encountered an issue where the corners of my carousel display as rounded, then sharp, and back to rounded during transitions. The problem is quite literally in the title. What is shown right after transition: https://i ...

Using AJAX with Django's CreateView functionality

I am looking to utilize generic views and modals with AJAX in Django for creating, updating, and deleting objects. In the official Django documentation, the AjaxableResponseMixin is discussed along with this code snippet: from django.http import JsonRespo ...

Using jQuery, identify when any of the elements within every function are missing

In my JavaScript file, I have the following code snippet: var aryYears= []; $(".year").each(function(){ aryYears.push($(this).val()); }) This allows me to pass an array of years as a parameter in the saveChanges function. I want to make ...

What is the purpose of a form that includes a text input field and a button that triggers a JavaScript function when the enter key is pressed?

<form action=""> <input id="user_input" onKeyDown="if(event.keyCode == 13)document.getElementById('okButton').click()" > <input id="okButton" type="button" onclick="JS_function();" value="OK"> </form> I'm trying to a ...

`Firefoxx border table glitch`

When attempting to open/close tables in Firefox using this link, unnecessary borders appear. https://i.sstatic.net/4tQCE.gif One way to fix this issue is by implementing the following JS solution: setTimeout(function () { $table.css({'table-la ...

Create beautiful HTML forms with Laravel Collective Forms in Laravel 5.7

I am currently using the Laravel Collective form code shown below: {!! Form::open(['action' => ['CategoryController@sub8', $item1->id], 'method' => 'post']) !!} {{Form::label('postaladdress', &apos ...

What is causing my PHP script to handle NULL values when making an AJAX request?

I am facing an issue where PHP is returning NULL instead of the expected data when interacting with AJAX. Check out the relevant code snippets below: header.php <?php include_once("obtainData.php"); ?> <!DOCTYPE html> <html lang="es"&g ...

Adjustable dimensions and proportions for the following image

I'm currently working on a blog page using next.js and I've encountered an issue with displaying images. Each post has a main image of varying dimensions and aspect ratios, making it difficult to maintain consistency when scaling for smaller scre ...

The height of the Material UI dropdown is displaying in an improper manner

I'm currently experimenting with the Material UI dropdown on my website, utilizing the react-select library. However, I've encountered an issue where the UI gets compromised when using an option that exceeds the width of the dropdown. If anybody ...

Repeater employs Endless Scrolling feature within DotNetNuke

I've integrated DotNetNuke into my custom module and I'm following the standard ASP.NET programming techniques (dragging/dropping). The project involves a posting service that uses a repeater with infinite scrolling and a masonry effect. I have f ...

An instructional guide on utilizing Python to extract the URLs of companies from a LinkedIn search

I'm having an issue extracting company profile URLs from a LinkedIn search as I keep getting a "not found" message. Despite my code running smoothly, the problem persists. Here is my code: import requests import csv import time import numpy from bs4 ...