Darren Bachan Darren Bachan - 6 months ago 11
Javascript Question

hasClass is not working when page is refreshed

I'm trying to say if

body
has x class to add x class.

Javascript

$('body').toggleClass('projectLoaded');
$('[data-type="projectLoader"]').click(function() {
var proj = $(this)[0].getAttribute('data-project');
$('#arrow-nav').addClass('slideIn');

updateHash(proj);
return false;
});
$('[data-type="projectDie"]').click(function() {

$('body').removeClass('projectLoaded');
$('#arrow-nav').removeClass('slideIn');
return false;
});

if ($('body').hasClass('projectLoaded')) {
$('#arrow-nav').addClass('slideIn');
} else {
$('#arrow-nav').removeClass('slideIn');
}


When
projectLoaded
is triggered, the
addClass
does work for
slideIn
, but when I refresh, even though
projectLoaded
is active, the
addClass
disappears. I thought a
hasClass
would work but it doesn't. Everything works but, it's just on refresh it disappears.

Working page here, click a project and you'll
#arrow-nav.slideIn
working, but refresh and the
.slideIn
isn't added.

UPDATE
This is what worked for me:

$( 'document' ).ready(function() {
if ($('body').hasClass('projectLoaded')) {
$('#arrow-nav').addClass('slideIn');
} else {
$('#arrow-nav').removeClass('slideIn');
}
});


or

$( 'body.projectLoaded' ).ready(function() {
$('#arrow-nav').addClass('slideIn');
});


If this is not proper or there's a more efficient way of doing this please submit it below.

Answer

checking ready as follows may help

$( document ).ready(function() {
    console.log( "ready!" );
    $('body').toggleClass('projectLoaded');
});

My instinct tells me this will work to, but didnt test it.

$( 'body' ).ready(function() {
    console.log( "ready!" );
    $('body').toggleClass('projectLoaded');
});