JoeDarsh
JoeDarsh

Reputation: 11

Jquery add CSS value not working

I've got some code that adds a CSS class to an element when the user scrolls to a certain amount, to make a sticky menu bar (The distance to scroll is dependant on screen resolution so is calculated within the JQuery) - I want to add a CSS value to this class (.header_scroll) so that it changes the height of the element the class is being assigned to on scroll, to the height of another dynamic height element (#nav_wrap)

jQuery("document").ready(function($){

        //Find the height of the header
        var headHeight = $("#header_wrap");
        var headerHeight = headHeight.innerHeight();

        //Find the height of the nav bar
        var menuFindHeight = $("#nav_wrap");
        var menuHeight = menuFindHeight.innerHeight();

        //Add value to class
        $(".header_scroll").css({"height": menuHeight});

        //Add class on scroll
        var nav = $('#header_wrap');

        $(window).scroll(function () {
            if ($(this).scrollTop() > ( headerHeight - menuHeight )) {
                nav.addClass("header_scroll");
            } else {
                nav.removeClass("header_scroll");
            }
        });

    });`

The code to add the class is working fine, however no matter what variations on this I try, the:

//Add value to class
        $(".header_scroll").css({"height": menuHeight});

Section will just not do anything at all. Looking in inspect element in chrome I'd expect to see

height: xxxpx;

appear in .header_scroll but it isn't

Upvotes: 0

Views: 128

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Maybe you can't get the right value of headerHeight, that why it doesn't appear in your inspect tools.

Check that you get the correct height of your #headHeight element and try this:

$(".header_scroll").height(headerHeight);

Upvotes: 0

MrUpsidown
MrUpsidown

Reputation: 22497

$(".header_scroll").css({"height": 200});

This will not add a height property to your CSS rule. Instead it will add style="height: 200px;" to the .header_scroll HTML element(s).

So you would end up with an HTML element like:

<div class="header_scroll" style="height: 200px;"></div>

Upvotes: 2

Related Questions