Search code examples
javascriptjqueryhtmlcssfade

Fade div in and out with JQuery


I'm losing my mind here.....

I wanted to fade in and out a div on the same page. I don't know JQuery so I started searching the thing I wanted.

I found this. It does exactly what I want it to do (in the Fiddle).

So I started copying and stuff but I just won't work

Here is what I did....

In my <head> I added the JQuery and CSS style

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$('#btn').click(function(e){    
    $('#fancy, #btn').fadeOut('slow', function(){
        $('#bank, #btn-bk').fadeIn('slow');
    });
});

$('#btn-bk').click(function(e){    
    $('#bank, #btn-bk').fadeOut('slow', function(){
        $('#fancy, #btn').fadeIn('slow');
    });
});
</script>
<style>
#bank {display:none;}
#btn-bk {display:none;}
</style>

In the body I placed the HTML

<div><a href="#" id="btn">Show bank div and hide fancy div</a></div>
<div id="btn-bk"><a href="#">back</a></div>
<div id="bank">Bank Div</div>
<div id="fancy">Fancy Div</div>

It does nothing. I don't see what I'm doing wrong!

M.


Solution

  • The one difference is their methods are defined in the jquery onload method. When JQuery tries to bind to the elements, they're not actually there yet! Try wrapping your Javascript like this...

    $(window).load(function(){
    $('#btn').click(function(e){    
        $('#fancy, #btn').fadeOut('slow', function(){
            $('#bank, #btn-bk').fadeIn('slow');
        });
    });
    
    $('#btn-bk').click(function(e){    
        $('#bank, #btn-bk').fadeOut('slow', function(){
            $('#fancy, #btn').fadeIn('slow');
        });
    });
    });