Thomas
Thomas

Reputation: 5089

Toggle div question

Im trying to toggle some divs and its not working, here is the js:

<script type="text/javascript">
        $(function(){   

            $('#toggle_full').click(function(){         
                $('#full_size').removeClass('toggle');
                $('#thumb_list').addClass('toggle');
            });
        });

        $(function(){   

            $('#toggle_thumb').click(function(){            
                $('#thumb_list').removeClass('toggle');
                $('#full_size').addClass('toggle');
            });
        });
    </script>

Here are the anchors:

<div class="toggle_block">
        <a href="#" id="toggle_full"><img src="img/full_icon.jpg" alt="#"/></a>
        <a href="#" id="toggle_thumbs"><img src="img/thumbs_icon.jpg" alt="#"/></a>
    </div>

Here is the class:

.toggle {
display: none;
}

Now where is the problem?

Upvotes: 2

Views: 250

Answers (2)

user113716
user113716

Reputation: 322452

Your ID's don't match.

In your HTML you have toggle_thumbs, but in your code you have toggle_thumb.


If all you're doing is hiding and showing, you can greatly simplify your code like this:

http://jsfiddle.net/xTPU8/2/

$(function() {
    var $elems = $('#toggle_full').hide()
        .add('#toggle_thumb').click(function() {
            $elems.toggle();
    });
});​

EDIT: Made it even a little more efficient.

Upvotes: 6

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

Add a return false; in your .click() delegate to prevent the browser from navigating to '#' (jumps to top of page).

You can also simplify your JS but putting both of your link bindings in the same, and using hide() and show() as already suggested. The end result would be:

<script type="text/javascript">

    $(function() {   

        $('#toggle_full').click(function() {         
            $('#full_size').show();
            $('#thumb_list').hide();
            return false;
        });


        $('#toggle_thumb').click(function() {            
            $('#thumb_list').show();
            $('#full_size').hide();
            return false;
        });

    });

</script>

Upvotes: 1

Related Questions