Kamal
Kamal

Reputation: 73

Using .append() with click() every time on div

I'm trying to change the text in a div every time I click on it. I tried the following, but its not working:

<script>
    $(document).ready(function() {
        //alert('hi');
        $('div').css('cursor','pointer')
        $('div').append('hi')

        $('div').click(function() {
            if ($(this).html('hi') {
                $(this).html('how r u');
            }
            if ($(this).html('how r u')) {
                $(this).html('hi');
            }
        )

        //$(this).html('how r u');
    })
})
</script>

Can anyone help me?

Thanks in advance

Upvotes: 0

Views: 181

Answers (3)

tusar
tusar

Reputation: 3424

<script>
$(document).ready(function(){
    $('div').css('cursor','pointer')
    $('div').append('hi')
    $('div').click(function(){
        if($(this).html() == 'hi')
        {
            $(this).html('how r u');
        }
        else if($(this).html() == 'how r u')
        {
            $(this).html('hi');
        )
    });
});
</script>

This will work too :

<div>hi</div>
<div style="display: none">how r you</p>
<script>
$("div").click(function () {
    $("div").toggle();
});
</script>

Upvotes: 0

m90
m90

Reputation: 11822

You still do need to compare the return value of the .html() methods:

if ($(this).html() === 'hi'){
   $(this).html('how r u');
} else if ($(this).html() === 'how r u'){
   $(this).html('hi');
}

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Instead of:

if ($(this).html('hi'))

try:

if($(this).html()==='hi')

Full code (you also forgot an "else" with your second "if"):

$(document).ready(function() {
    $('div').css('cursor', 'pointer');
    $('div').append('hi');

    $('div').click(function() {
        if ($(this).html() === 'hi') {
            $(this).html('how r u');
        } else if ($(this).html() === 'how r u') {
            $(this).html('hi');
        };
    });
});​

http://jsfiddle.net/HKWdT/

Upvotes: 1

Related Questions