Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text onclick and make other change back to default?

I have some similar text ("More about us"), i have made it change to another ("Less about us") when click and change back when click again. But now i need a solution to when i click one (first line for example and just once) and then click another (second line this time), the first line (now show "Less about us") change back to "More about us" while the second line still change to "Less about us".

HTML

<span class="more">More about us</span><br/><br/>
<span class="more">More about us</span><br/><br/>
<span class="more">More about us</span><br/><br/>
<span class="more">More about us</span><br/><br/>
<span class="more">More about us</span>

JS

$('.more').click(function() {
    var s = $(this);
    s.html(s.text() == 'More about us' ? 'Less about us' : 'More about us');
});

This is the demo

like image 456
Henry Varro Avatar asked Jul 14 '15 10:07

Henry Varro


2 Answers

Change your Javascript to:

$('.more').click(function() {
    var s = $(this);
    var originaltext= s.text();
    $('.more').text('More about us');  
      s.text(originaltext);
    s.html(s.text() == 'More about us' ? 'Less about us' : 'More about us');

});

What it does it:

  1. Store the text of current clicked span.
  2. Change all the spans to 'More about us'.
  3. Change current text to the original.
  4. Continue with normal functionality.

See the fiddle : "http://jsfiddle.net/HFcvH/35/"

EDIT: This can also be done using .siblings() as follow:

$('.more').click(function() {
    var s = $(this);

    $(this).siblings().each(function() {
        $(this).text('More about us');  
    });

    s.html(s.text() == 'More about us' ? 'Less about us' : 'More about us');

});

Explanation: This will iterate over all the siblings of current element and reset their text.

See the fiddle: "http://jsfiddle.net/ee24gcdj/1/"

It can be further reduced using(thanks Ted Nyberg for the information):

$(this).siblings().text('More about us')
like image 177
Nikhil Batra Avatar answered Oct 20 '22 00:10

Nikhil Batra


Here is the fiddle: http://jsfiddle.net/kge7dbLa/1/

$(".more").on("click", function() {
    var s = $(this);

    /*  Just add this line of Code  */
    $(".more").text('More about us');

    s.html(s.text() == 'More about us' ? 'Less about us' : 'More about us');
})
like image 33
mechanicals Avatar answered Oct 19 '22 22:10

mechanicals