Nicero
Nicero

Reputation: 4377

understanding clicks behaviour

I wrote this simple code to understand why if I click the "click me" text for the second time JQuery does not display the "second" text.

<div id="clickme">Click me</div>
<div id="sometext">This is text ZERO</div>

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

        $("#clickme").click(function(){ 
            if (a == 1) {
                $('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
            }
            else {
                $('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
                var a = 1;
            }
        });

    });
</script>

I expected the following behaviour:

  1. Page is loaded and the text 'This is text ZERO' is displayed
  2. I click the link the first time and JQuery displays 'This is text ONE'
  3. I click the link a second time and jQuery displays 'This is text TWO'

Instead point #3 is not processed or at least the text is not displayed. Why?

Upvotes: 0

Views: 52

Answers (2)

John Hartsock
John Hartsock

Reputation: 86882

Because a is defined locally, it is a scope issue. Initialize a globally and it will work. See Below

$(document).ready(function($) {
   var a = 0;
   $("#clickme").click(function(){ 
     if (a == 1) {
       $('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
     }
     else {
       $('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
       a = 1;
     }
   });
});

Here is a fiddle

http://jsfiddle.net/jfhartsock/Khp7P/1/

Upvotes: 2

Terry
Terry

Reputation: 14219

It is a scope issue as mentioned above, the variable 'a' must be defined in the scope of the page, not the click event.

$(document).ready(function($) {
    var a = 0;

    $("#clickme").click(function() {
        if (a == 1) {
            $('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
            a = 0;
        }
        else {
            $('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
            a = 1;
        }
    });
});

http://jsfiddle.net/d5xSH/

Upvotes: 2

Related Questions