Can I dynamically apply CSS to an existing class using jQuery?

Having a sticky sidebar on desktop presents a challenge when trying to "unstick" it before it overlaps with the footer. The height of the sidebar is dynamic, so its stop position changes as different elements are opened or closed.

The main question at hand is how to add:

css('top', dynamic-value);

to an EXISTING class in order to temporarily "unstick" the sidebar once it reaches the footer, and then resume normal sticky navigation by removing this specific class containing the dynamic top value.

Attempting to add the CSS using the following code snippet results in the styles being added directly to the DOM instead of applying them to the specified class:

element.addClass('not-sticky')
$('.not-sticky').css('top',dynamic-value);

Consequently, upon removing the class, the added CSS remains in the DOM causing disruptions. Is there a way to add CSS to an existing class without affecting the DOM structure? Alternatively, is there a method to remove dynamically added CSS from the DOM?

//css
@include respond-to(desktop) {
        width: 310px;
        float: left;

    &.fixed {
        top: 20px;
        height: auto;
        position: fixed;
        }

    &.not-fixed {
        //top: 5656px;
        position: absolute;
    }

}

//jquery
$(document).scroll(function() {

        scrollTop = $(document).scrollTop();
        sidebar = $(".sidebar");
        sidebarFixed = sidebar.hasClass("fixed");
        sidebarHeight = sidebar.height();
        var footerTop = $('.footer').offset().top; // where footer starts

        // FIXED desktop navigation conditions
        var stickyDesktop = scrollTop > (sidebarOffset - 20);

        // STOP being sticky navigation condition
        // when the sidebar has scrolled far enough from the top of the document (scrollTop)
        // that the bottom of the sidebar (sidebar Height) hits the top of the footer (footerTop)
        // the 120 is to account for spacing between the top of the footer and bottom of sidebar
        var stickyLimit = (scrollTop + sidebarHeight + 120) > footerTop;


        // this is to be the top: diff for the .not-fixed class
        var diff = scrollTop - stickyLimit;

        if(windowWidth >= 1080) {
            // on desktop make sidebar sticky on scroll
            stickyDesktop = scrollTop > (sidebarOffset - 20);
            sidebar.toggleClass('fixed',stickyDesktop);

            // if the navigation is sticky
            if(sidebarFixed === true) {
                pageIntro.slideUp(300);
            } else {
                pageIntro.slideDown(300);
            }

            // if condition to stop fixed navigation is met
            if (stickyLimit === true) {

                stickyLimit = (scrollTop + sidebarHeight + 120) > footerTop;

                // stop nav being sticky
                sidebar.addClass('not-fixed');
                // THIS CSS DOESN'T GET ADDED TO THE CLASS BUT TO THE DOM
                $(".not-fixed").css('top',diff);


            } else {
                // regular sticky again
                sidebar.removeClass('not-fixed');
            }
        }

    }); // end document scroll function

Answer №1

It is not possible to directly add or remove CSS from an external stylesheet.

However, in your situation, you can undo the styling applied to an element by resetting the top property back to 0.

$('.not-fixed')
     .css('top',0)
     .removeClass('not-fixed');

Answer №2

My approach involved overriding the CSS modifications made through jQuery by executing the following code:

 $(".element").css("top"," ");

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

How do I change the class of an element using $this?

Please review the code below: $(".nwe-cl-icontext").click(function () { $(this).parent().toggleClass("nwe-active"); }) .nwe-cl-c.nwe-active { background: red; } .nwe-cl-c { background: green; } <scrip ...

Transmitting data via POST method within datatables ajax call

I am facing an issue while attempting to execute a simple ajax call in datatables that relies on a post array of IDs from a form on a previous page. The error I encounter is: Invalid JSON Response This indicates that the JSON array being returned may be ...

Retrieving Text Between HTML Tags Using jQuery

Disclosure: I am fully aware of the messy HTML code in this legacy application. Unfortunately, due to its extensive dependencies, making any changes to the HTML structure is not feasible. Despite the circumstances, here is the code snippet at hand: <t ...

I'm having trouble getting the animation to work with jQuery. Despite trying everything, the animation doesn't seem to respond to any button clicks

Issue: I am facing a problem where nothing happens when I click the menu on the HTML page. It seems like a total beginner mistake, but I can't seem to get it to work. I have checked the code, and alert works fine, indicating that jQuery is connected t ...

Loading Animation with jQuery and Minimum Time Delay

Hello there, I am looking for a way to establish a minimum time duration for an onload function to ensure that a div is displayed for at least 2 seconds. Similar to setting a min-width or min-height, I want the div to be shown for a minimum of 2 seconds e ...

How can I dynamically unload a JavaScript file that was previously loaded with RequireJS? Alternatively, how can I handle exclusive dependencies or reset RequireJS?

I'm facing a dilemma with two JavaScript files that cannot be loaded simultaneously. One needs to be unloaded before the other can be loaded when a specific button is clicked. Here's an outline of my current approach: //pseudocode if user click ...

Using Javascript and jQuery, populate a dropdown menu with options that are extracted from a different dropdown menu

These are my two <select> elements: <select class="js-select-1"> <option disabled>Starting point</option> <option>A</option> <option>B</option> <option>C</option> <option>D</op ...

Having trouble selecting content in an HTML document using Xpath and response.css with Scrapy?

Something is quite puzzling me and I've been pondering over it for almost a week now. Perhaps the solution is staring right at me and I just can't see it clearly... Any hints for alternative approaches would be greatly appreciated. I have n ...

Although hiding and showing elements in jQuery is quick, the rendering engine is too sluggish

Experiencing a performance problem when toggling the visibility of all "tr.content" elements within a complex dom structure like this:    <tbody class="collapsible">        <tr class="handler">            <td>Collaps ...

Different sized image grid display

Could you please take a look at this screenshot: I am facing an issue with the grid layout. The first image in the grid is too short, which results in a big gap between the upper left and lower left pictures. Here is what it looks like currently: Is ther ...

Use both a PayPal form and a PHP form simultaneously by implementing a single button that can submit both forms with the help of jQuery and AJAX

While I have a good grasp on HTML and PHP, my knowledge of jQuery and Ajax is quite limited. After spending a significant amount of time searching for answers here: One form, One submission button, but TWO actions and here : Writing to my DB and submittin ...

Searching and replacing query strings in a URL using JQuery according to the chosen option in an HTML dropdown menu

Is there a way to use jQuery to dynamically change a specific value in the query string by finding and replacing that value based on the selection made from a dropdown menu on the webpage? For example: Imagine we have this query string on the current page ...

Using Selenium to choose an element based on the text of its sibling element

I've been working on a selenium script for: My goal is to select the "Add to Compare" element for "Sony Xperia," but it's not being located. I've tried using both cssSelector and xpath, but I can't seem to figure out what I'm doin ...

Is there a way to trigger a function within the submit handler with jQuery validation?

I've been attempting to trigger an ajax function once the form is validated, but I'm running into some issues. The jQuery on-submit method below is working perfectly for me. $('#promotionAdd').on('submit',(function(e) { ...

What is the correct method for attaching event listeners to newly added elements following an AJAX request for HTML content? (Using jQuery or JavaScript)

I'm working on a project where new setting pages are loaded via AJAX. I'm trying to figure out the best way to bind listeners to elements in the new content. One idea I had is to create a function that checks the file path and applies appropriat ...

Simultaneous CSS3 animations on a pair of items

I am facing a styling challenge with a wrapper div that is positioned absolutely on the side of the page. Inside this wrapper, there is an unordered list of items. Here is the HTML structure: <div id="wrapper"> <ul class="menu"> ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Revise Panel timer management with the power of JQuery

Within our Update Panel, we have a variety of controls such as HTML divs, tables, and grids. We also utilize an AsyncPostBackTrigger with the Tick event of a timer control, which updates the panel at specified intervals. Some controls are loaded using JQue ...

Assistance with HTML and CSS to position an image in the corner

I need assistance with positioning a corner image on top of another image. I want the span, which has a small background image, to be in the top left corner of the main image. Below is my code: <div id="wrapkon"> <span style="width: 4px; height: ...

Troubleshooting Handlebars XML Parsing Issues on Firefox

As a newcomer to handlebars, I've recently integrated it into my project and things have been running smoothly. However, I've encountered some errors in my Firefox console (both Developer edition and normal). It's important to note that I am ...