The addClass and removeClass functions seem to be malfunctioning

Hey everyone, this is my first time reaching out for help here. I looked through previous questions but couldn't find anything similar to my issue.

I'm currently working on a corporate website using bootstrap3 in Brackets. I've been testing it on the latest versions of Chrome and Safari.

The problem I'm facing is trying to shrink the navbar's height and change its background color using JQuery addClass and removeClass, but unfortunately, it's not working at all. Interestingly, changing CSS properties via JQuery does work, specifically changing the background color. However, when attempting to alter multiple CSS properties via JQuery, it just doesn't seem to cooperate and only allows me to modify the background color.

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").addClass('animated-header');
    } else {
      $("#top-bar").removeClass('animated-header');
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })

}); //this is the part that’s causing trouble

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").css("background-color", "#ef7c7c");
    } else {
      $("#top-bar").css("background-color", "transparent");
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })
}); //this section works perfectly
#top-bar {
  background: transparent;
  color: #fff;
  -webkit-transition: all 0.2s ease-out 0s;
  transition: all 0.2s ease-out 0s;
  padding: 30px 0;
  height: 15%;
}
#top-bar .animated-header {
  /*Background Color of nav bar when scrolled*/
  background-color: #ef7c7c;
  padding: 10px 0;
  height: 10%;
  -webkit-box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
}
<header id="top-bar" class="navbar-fixed-top animated-header">
  <div class="container">

Thank you all so much for your assistance!

Answer №1

The issue lies not with the JS utilizing .addClass(), but rather with the incorrect selector in your CSS. Like so:

#top-bar .animated-header {

Should actually be written as:

#top-bar.animated-header {

This means we should eliminate the space before the ., since if there is a space, the selector will target elements with the class animated-header that are children of the #top-bar. However, without the space, it will target the #top-bar itself if it has the animated-header class.

Answer №2

Your CSS code contains an error that needs to be corrected:

#main-content .special-header
    /*   ^      
        There is a mistake here; you have assigned these properties to an element that should be a child of the #main-content
        element
    */

Here is the corrected version:

#main-content.special-header

Answer №3

It is advisable to apply all styles using CSS for better organization. To fix the issue with extra space in your selector, change #top-bar .animated-header to #top-bar.animated-header. However, if you prefer to apply styles using jQuery, you can use the following code:

$(document).ready(function(){
    $(window).scroll(function () {
        if ($(window).scrollTop() > 50) {
            $("#top-bar").addClass('animated-header').css({'background-color': '#ef7c7c', 'height': '10%'});
        } else {
            $("#top-bar").removeClass('animated-header').css({'background-color': '', 'height': ''});
        }
    });
});

$(document).ready(function(){
    $(window).scroll(function () {
        if ($(window).scrollTop() > 50) {
            $("#top-bar").addClass('animated-header');
        } else {
            $("#top-bar").removeClass('animated-header');
        }
    });
});
body {
  height: 1000px;
}
#top-bar {
  background: transparent;
  color: #fff;
  -webkit-transition: all 0.2s ease-out 0s;
  transition: all 0.2s ease-out 0s;
  padding: 30px 0;
  height: 15%;
}
#top-bar.animated-header {/*Background Color of nav bar when scrolled*/
  background-color: #ef7c7c;
  padding: 10px 0;
  height: 10%;
  -webkit-box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header id="top-bar" class="navbar-fixed-top animated-header">
            <div class="container">

Answer №4

There seems to be a small issue with your snippet, specifically when adding CSS. It should be #top-bar.animated-header instead of #top-bar .animated-header.

$(document).ready(function() {
 $(window).scroll(function () {

if ($(window).scrollTop() > 50) {
   $("#top-bar").addClass('animated-header');
   
} 
else {
       $("#top-bar").removeClass('animated-header');  
   
}
});


});
#top-bar {
    position:fixed;
 top:0;left:0;
  background: transparent;
  color: #fff;
  -webkit-transition: all 0.2s ease-in 0s;
  transition: all 0.2s ease-in 0s;
  padding: 30px 0;
  height: 15%;
}
#top-bar.animated-header {
  /*Background Color of nav bar when scrolled*/

  background-color: #ef7c7c;
  padding: 10px 0;
  height: 10%;
  -webkit-box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="top-bar" class="navbar-fixed-top animated-header">
  <div class="container">
   logo
    </div></header>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

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

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

jQuery AJAX delivering HTML output upon completion

Currently, I am implementing a jQuery Ajax function to submit the username and password and receive a response. The functionality works seamlessly with the GET method. However, when using the POST method, it successfully sends the data but fails to retur ...

What is the best way to retrieve an element that has been altered in its state?

I encountered a scenario where I want an image to have a border when clicked, and if clicked again, the border should be removed. However, the border should also be removed if another image is clicked instead. I believe there are a couple of approaches to ...

React- Struggling to modify state from child component using function declared within a parent component

This is my main component: import React, {useState} from 'react'; import SearchBar from '../components/SearchBar'; import WeatherDisplay from '../components/WeatherDisplay'; import LocationInfo from '../components/Locat ...

RegEx for capturing targeted content within HTML elements

I am in need of developing a Python program that takes an HTML file from the standard input, then outputs the names of species listed under Mammals to the standard output line by line utilizing regular expressions. Additionally, I am instructed not to incl ...

Update the CSS of a different element when hovering

Hello to all the jQuery developers out there! I have a question that's fairly simple. I'm trying to change a CSS attribute for an element when I hover over a different element on the page. I've created a fiddle for you to review, and I&apos ...

Increase division height when mouse hovers over it

I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...

Trigger function in React after the page finishes loading

I have a scenario where I need to display images onDrop within one of my components. To ensure a smooth drop experience, I am considering preloading the images using the following approach: componentDidMount(){ this.props.photos.forEach(picture => ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...

What is the process for ensuring that an image is set as the submit button in an HTML form on IE 7?

My HTML form is designed with an action on a PHP script, and the submit button displays a custom image instead of the default grey. While this code works perfectly in Chrome, it fails to function properly in Internet Explorer 7. Do you have any suggestions ...

Exploring the Best Methods to Retrieve the data-id in jstree JSON data

My goal is to retrieve the data-id from a dynamically generated tree form using JsTree (which has checkboxes), but unfortunately, my current approach isn't working. To iterate over the checkboxes and account for multiple selections, I am utilizing the ...

What is the way to determine the length of a list in a velocity template?

Is there a way to determine the size of a list in a velocity template? I am currently working with version 1.4 of Velocity. List<String> list = new ArrayList<String>(); ...

How can I make a div blur as I scroll through the page

How can I make each item in my timeline focused one at a time as the user scrolls, instead of having all items in focus simultaneously? Any ideas or suggestions would be appreciated. Here is my fiddle and here is my code $(document).ready(function(){ ...

In search of an effortless solution to fetch the hostname, computer name, and IPV6 address utilizing ASP or VB6

In search of an effortless method to retrieve the computer name, host name, and ipv6 ipaddress using vb6, asp, or jQuery. The primary motivation for this task is to ensure comprehensive logging of crucial security information. ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

HTML5 - Adding Space to Main Section with a Two-column Layout

After spending 3 and a half hours racking my brain, I still can't figure out how to complete two seemingly simple tasks. First, I need to pad the outside of paragraph div, and secondly, I want to split the main section into two columns to add some lin ...

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...