Gradislava Bikkulova
Gradislava Bikkulova

Reputation: 331

Callback function issue jquery

I have an issue with an if in a callback function and I don't understand why.

After clicking on a div, the text is changing as I would like, but after the first shot it doesn't work anymore.

My code is :

<div id="2">message</div>
<div id="1">dfdfgdfgrr</div>

<script src="jquery.js"></script>
<script>
$(function () {

$('#2').toggle();

function test() {
    $(document).on('click', '#1', function () {
        $('#2').toggle(300, function() {
            if($('#1').text('show')){
                $('#1').text('hide');
            }else{
                $('#1').text('show');
            }
        });
   });
}

test();


});
</script>

http://jsfiddle.net/manguo_manguo/cydjY/

Upvotes: 0

Views: 290

Answers (4)

Guern
Guern

Reputation: 1257

The other solution are correct, but the first time it is not shown the show label.

This is a complete solution:

$(function () {

$('#2').toggle();

function test() {
    $(document).on('click', '#1', function () {
        $('#2').toggle(300, function() {
            if($('#1').text() == 'hide'){
                $('#1').text('show');
            }else{
                $('#1').text('hide');
            }
        });
   });
}

test();
$('#1').text('show');
});

Try an example here

Upvotes: 1

user1466291
user1466291

Reputation:

$('#1').text(function(i, t) { return t == 'show' ? 'hide' : 'show' });

Upvotes: 1

Jean-Philippe Bond
Jean-Philippe Bond

Reputation: 10649

You are using $('#1').text("show") instead of $('#1').text() == "show"

$('#2').toggle();

function test() {
    $(document).on('click', '#1', function () {
        $('#2').toggle(300, function() {
            if($('#1').text() == 'show'){
                $('#1').text('hide');
            }else{
                $('#1').text('show');
            }
        });
   });
}

test();

Upvotes: 1

K D
K D

Reputation: 5989

      if($('#1').text() === 'show'){
            $('#1').text('hide');
        }else{
            $('#1').text('show');
        }

Upvotes: 1

Related Questions