treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Need to add padding to top of headers

  • Hi, I'm trying to add padding to the top of the h1 and h2 headers at this site when they are clicked. When the navbar is collapsed (i.e. < 980px) padding is added. But when the navbar is full width, it is not.

    debbierking.com/bootstrap

    I tried this script, but it's not working

    $(document).ready(function() {
      $('.nav li a').click(function() {
          $('h1, h2').appendTo('.toppad');
      });
    

    });

    CSS:

        .toppad {
    margin-top: 25px;
    

    }

    I tried to set this up in codepen, but when I click the links, the content disappears.

    http://codepen.io/anon/pen/BiIln

  • You were on the right track . . . roughly. This is what you want, I think:

    $(document).ready(function() {
        $('.nav li a').click(function() {
            $('h1, h2').addClass('toppad');
        });
    });
    

    http://codepen.io/JoshBlackwood/pen/bipBE

  • Thanks Josh! That works great! I originally started with addClass but when it didn't work, switched to AppendTo...I had some other things wrong in the code though, which I have since fixed.

    Once again, though I need this only to work for 980px and higher as Bootstrap appears to already add top padding to the headers when the nav bar is collapsed. I tried using some of the code from the other script you are helping me with (removing the Overlay function) but that didn't work.

  • In that case, just add an if statement around the click event, like so:

    $('.nav li a').click(function() {
        if ( $winWidth.width < 980 ) {
          $('h1, h2').addClass('toppad');
        } else {
          $('h1, h2').removeClass('toppad');
        };
      });
    

    And put this in the same script block as where the $winWidth variable is defined.

  • Just can't get the width thing to work...this removes all the padding for all widths...Tried a variation of this yesterday with the same result.

  • It looks like you're still putting this in a separate script block. This needs to go in the same script block as the other width function I've been helping you with, as it's using a common variable.

  • Looks like this is resolved, thanks to an answer posted here: http://stackoverflow.com/questions/7306933/how-to-detect-window-size-and-then-do-something-with-jquery-switch-statement.

    Thanks so much for your help!

      $(document).ready(function() {
    

    var width = $(window).width(); if (width > 979 ) { $('.nav li a').click(function() {
    $('h1, h2').addClass('toppad'); }); } });