jarrodwhitley
jarrodwhitley

Reputation: 828

Why is my jQuery .css() code not applying styles?

I looked about multiple existing posts and none had a solution for me.

Edit: Someone asked why I'm using jQuery(document).ready(function($). This is a Wordpress site. You have to wrap your jQuery like this if you want to use $ since $ is used by the Wordpress framework and will break your code.

Update

Here is the code that creates the button dynamically. I wouldn't have done it this way, but I've inherited the site when I started working here:

$('nav').before('<button class="menu-btn" role="button" aria-pressed="false"><span>toggle menu</span></button>'); 
        $('nav .sub-menu').before('<button class="sub-menu-toggle" role="button" aria-pressed="false"></button>'); 

Not only are the styles not being applied, they are not even visible in dev tools so I know they're not simply being overridden by inline styles or something. The jQuery css isn't being loaded at all.

Details:

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

  $('.site-title').css({
    'grid-column-start': '2',
    'grid-column-end': '6'
  });

  $('.menu-btn').css({
    'top': 'unset',
    'right': 'unset',
    'left': '10px',
    'bottom': '15px',
    'z-index': '100',
    'position': 'fixed'
  });
});

When the same styles are added via CSS they apply correctly.

body > div.site-container > button.menu-btn {
  top: unset;
  right: unset;
  bottom: 15px;
  left: 10px;
  z-index: 100;
  position: fixed;
}

Upvotes: 2

Views: 284

Answers (1)

jarrodwhitley
jarrodwhitley

Reputation: 828

@MDrX figured it out. My .menu-btn was being created dynamically so added my code to the same block that created the button and it worked!

Final result:

    // Add Mobile Menu Button
    $('nav').before('<button class=".menu-btn" role="button" aria-pressed="false"><span>toggle menu</span></button>'); // Add toggles to menus
    $('nav .sub-menu').before('<button class="sub-menu-toggle" role="button" aria-pressed="false"></button>');
    $('.menu-btn').css ({
        'top':'unset',
        'right':'unset',
        'left':'10px',
        'bottom':'15px',
        'z-index':'100',
        'position':'fixed'
    });

I'm posting the answer here for now, but I'm waiting to see if @MDrX will post an answer so that I can give him the credit and that sweet, sweet rep :)

Upvotes: 1

Related Questions