HikJ HikJ - 6 months ago 8
Javascript Question

Can't get basic jQuery logic to work

I have this button in my HTML that basically collapses/expands the

#leftmenu
and it's working okay:
<a id="menutoggle" data-toggle="collapse" data-target="#leftmenu">Placeholder</a>


I want to accomplish this:


  1. If
    #leftmenu
    is visible when you load the page then add
    top:-10px
    property to
    #contentfix
    .

  2. If
    #leftmenu
    is collapsed by clicking the collapse button then remove
    top:-10px
    property from
    #contentfix
    .

  3. If
    #leftmenu
    is expanded by clicking the collapse button then add
    top:-10px
    property to
    #contentfix
    .



I basically want the
top:-10px
property in my
#contentfix
whenever
#leftmenu
is visible and
top:0px
whenever it is hidden. Regardless of whether page had it visible/hidden by default or you changed it by clicking the collapse button.

Here's my current attempt:

if ($("#leftmenu").is(":visible")) {
$('#contentfix').css('top','-10px');
var visible = 1;
}

$('#menutoggle').click(function(e) {
$('html, body').animate({ scrollTop: 0 }, 'fast');
if (visible == 0){
$('#contentfix').css('top','-10px');
visible = 1;
} else {
$('#contentfix').css('top','0px');
visible = 0;
}
});

Answer

Make sure to use $(document).ready(). Moreover you can cache jQuery objects and do not need to set a visible variable and write the same functionality twice.

$(document).ready(function(){
    var contentFix = $('#contentfix');
    var leftMenu = $("#leftmenu");
    var menuToggle = $('#menutoggle');
    var htmlBody = $('html, body');
    var toggle = function(){
        htmlBody.animate({ scrollTop: 0 }, 'fast');
        if (leftMenu.is(":visible")) {
            contentFix.css('top','-10px');
        } else {
            contentFix.css('top','0px');
        }
    }
    menuToggle.on('click', function() {
        toggle();
    });
});