-2
$(document).ready(function() {
var page = 1;
    $(".btnReadMore").click(function(){
        if(page==1){
            $('#aboutUsText').text('textone');
            var page=0;
        }else{
            $('#aboutUsText').text('text two');
        }
    }); 
});

I am fairly new to javascript, I am trying to toggle an elements text when you press a button, What am i doing wrong? Thanks :3

2 Answers2

0

I wouldn't recommend using "var page = 1;" because it's a global variable and one should avoid global variable when possible because they are bad for performance.

$("#btnReadMore").click(function(){
    var textSpan = $('#aboutUsText');
    if (textSpan.attr("ShowState")=="2"){
        textSpan.text('textone');
        textSpan.attr("ShowState", "1");
    }else{
        textSpan.text('text two');
        textSpan.attr("ShowState", "2");
    }
});

In the above example, I declare my own custom attribute called ShowState and I save it on the label itself. Also, I switched the button an use an ID instead of class. Class is slow to access. ID is instant.

Checkout my fiddle: http://jsfiddle.net/eLVTk/

Yogesh Jindal
  • 592
  • 7
  • 20
  • This is working well in jsfiddle, However dosen't seem to be working when implimenting into my webpage. Here is my code: http://pastebin.com/v7yrKSnS – user3576711 Apr 30 '14 at 17:26
  • Please change to . You should only use class attribute when necessary, hence I changed the button to use id attribute. – Yogesh Jindal Apr 30 '14 at 18:10
0

Because you are re-declaring page within the function, the entire .click() event handler will always use the var page = 0. See variable scoping and variable hoisting.

As Dhaval stated in the comments, simply dropping the declaration will fix this:

 page = 0; // Instead of var page = 0
Community
  • 1
  • 1
Matt
  • 3,079
  • 4
  • 30
  • 36