简体   繁体   中英

Show/Hide div using if then statement (javascript)

I have this show/hide set up here: http://jsfiddle.net/TwDSx/38/

What I would like to do is have the plus sign go away if the content is showing and vise versa if the content isn't showing hide the minus sign and show the plus.

I read articles on this using images to swap out, but nothing with just using html/css. Also, I would like to keep the javascript out of the html if this is possible, and just call for it externally.

any help is appreciated!

EDIT :

You can attach an event handler on your click to toggle the display attribute of the + or - button

$('#hide,#show').click(function(){
  $('#hide,#show').toggle();
})

Quick demo: http://jsfiddle.net/TwDSx/39/

I modified your Javascript a little and extended it so you can keep it in an external file, you just need to ensure you hide the #show div with CSS if you load the page with the content already showing, or vice-versa for the #hide .

The Javascript is as follows:

$('#show').click(function() {
    ShowClick();
});  

$('#hide').click(function() {
    HideClick();
});

//This Javascript can be external
function ShowClick() {
    $('#content').toggle('slow');
    $('#hide, #show').toggle();
};

function HideClick() {
    $('#content').toggle('fast');
    $('#show, #hide').toggle();
};

The Js-Fiddle can be seen here: http://jsfiddle.net/mtAeg/

I think the simplest solution is to have only one button, #toggle , and to change the content of that button like so:

$('#toggle').click(function () {
    if (this.innerHTML == '-') {
        $('#content').slideUp('fast');
        this.innerHTML = '+';
    } else {
        $('#content').slideDown('slow');
        this.innerHTML = '-';
    }
});

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM