X9DESIGN
X9DESIGN

Reputation: 783

jquery | on click action works only first time

Why script from URL used below works only when i click the element first time, and after second not?

<span id="hider">hide</span>

<script type="text/javascript">
$('span#hider').click(function() {
    if($('span#hider:contains("hide")')) {
        $('span#hider').html('show');
    }
    else if($('span#hider:contains("show")')) {
        $('span#hider').html('hide');
    }
});
</script>

http://jsfiddle.net/c40hjnpq/

Upvotes: 2

Views: 1175

Answers (5)

Rahul K
Rahul K

Reputation: 413

$('#hider').bind('click',function(){
    var hider = $(this);
    var hiderval = $(this).html();
    if(hiderval.indexOf("show") > -1){
        $(this).html('hide');
    }
    else if(hiderval.indexOf("hide") > -1){
        $(this).html('show');
    }
});

fiddle: http://jsfiddle.net/c40hjnpq/23/

Upvotes: 0

codebased
codebased

Reputation: 7073

Just make it simple mate:

$('#hider').click(function() {
    var newValue =  $('#hider').html() === 'show'   ? "hide": "show";
    $('#hider').html(newValue);
});

Upvotes: 1

Nima Derakhshanjan
Nima Derakhshanjan

Reputation: 1404

try this :

$('span#hider').click(function() {
    if($('span#hider').text()=='hide') {
        alert($('span#hider').text());
        $('span#hider').html('show');
    }
    else if($('span#hider').text()=='show') {
        alert($('span#hider').text());
        $('span#hider').html('hide');
    }
});

Upvotes: 0

isogram
isogram

Reputation: 318

$('span#hider:contains("hide")')

This does not check whether or not the #hider contains the text 'hide', as it seem you think it does. What it does is make a list of all the span#hider elements that do contain that text. If none do, it returns a jQuery wrapper object.

Therefor, if you use if( $('yourSelector') ) and nothing with your selector is found, it will always return truthy, so your code never gets into the second if.

Instead, you should do this:

$('span#hider').click(function() {
    if($('span#hider').html() == "hide") {
        $('span#hider').html('show');
    }
    else if($('span#hider').html() == "show") {
        $('span#hider').html('hide');
    }
});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

the jQuery() constructor returns an object, which will always be true so your first if block is always executed

$('#hider').click(function () {
    if ($(this).is(':contains("hide")')) {
        $(this).html('show');
    } else if ($(this).is(':contains("show")')) {
        $(this).html('hide');
    }
});

Demo: Fiddle


But this can be simplified as

$('#hider').click(function () {
    $(this).html(function (i, html) {
        return $.trim(html) == 'hide' ? 'show' : 'hide';
    });
});

Demo: Fiddle

Upvotes: 2

Related Questions