Search code examples
jqueryfadein

jQuery simple .fadeIn demo not working for me


Why will this not work? I have been sitting here for hours as I am so confused... it works perfectly in jsFiddle http://jsfiddle.net/5SHdr/8/

<!DOCTYPE html>
<html>
<head>
<style>
body
{
    padding:0;
    margin:0;
}

#menu
{
    width:100%;
    background-color:#ddd;
}

#menu .link
{
    display:inline-block;
    margin-left:5px;
    margin-right:5px;
    padding:5px;
    cursor:pointer;
}
#menu .link.active
{
    color:blue;
}

#main
{
    padding:5px;
}

#main .content
{
    display:none;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$('.link').click(function () {
    if ($(this).hasClass('active')) return false;
    var name = $(this).attr('id');
    var $visible = $('#main .content:visible');
    $('.active').removeClass('active');
    $(this).addClass('active');
    if ($visible.length == 0) showContent(name);
    else $visible.fadeOut(500, function () {
        showContent(name);
    });
});

function showContent(name) {
    $('#main .' + name).fadeIn(500);
}
</script>
</head>
<body>
<div id="menu">
    <div class="link" id="home">Home</div>
    <div class="link" id="blog">Blog</div>
    <div class="link" id="about">About</div>
</div>
<div id="main">
    <div class="home content">This is the home content.</div>
    <div class="blog content">This is the blog content.</div>
    <div class="about content">This is the about content.</div>
</div>
</body>
</html>

Is there something really simple I am missing?


Solution

  • Your script is not inside dom ready, in fiddle in the left hand side panel second dropdown you have selected onload that means you script in the script panel will be executed on window load event.

    jQuery(function($){
        $('.link').click(function () {
          console.log('x')
            if ($(this).hasClass('active')) return false;
            var name = $(this).attr('id');
            var $visible = $('#main .content:visible');
            $('.active').removeClass('active');
            $(this).addClass('active');
            if ($visible.length == 0) showContent(name);
            else $visible.fadeOut(500, function () {
                showContent(name);
            });
        });
    })
    

    Demo: Plunker