0

$('.showlink').click( function() {
    $('.box').slideToggle(300);
});
.box {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showlink">click</div>
<div class="box">content</div>

I have my code like this and I want to change the word 'click' into 'click again' that's in the first div after clicking on it, but I don't know how to achieve this?

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Enma Nii
  • 123
  • 1
  • 12

3 Answers3

2

Use text() method like following to change text.

$('.showlink').click( function() {
    var text = $(this).text().trim();
    $(this).text(text == 'click' ? 'click again' : 'click');
    $('.box').slideToggle(300);
});
.box {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="showlink">click</div>

<div class="box">content</div>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
1

You can use the .text method of jQuery

 $('.showlink').click(function() {
   $(this).text("Click again");
   $('.box').slideToggle(300);
 });
.box {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="showlink">click</div>

<div class="box">content</div>

But you can get a bit speed/performance by modifying a bit your JS code. Here you use jQuery to select your DOM nodes each time you click. Since DOM access is really slow you can save the reference into a variable

(function() {
  "use strict";

  var $showLink = $('.showlink');
  var $box = $('.box');
  $showLink.click(function() {
    $showLink.text("Click again");
    $box.slideToggle(300);
  });

})();
 .box {
   display: none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="showlink">click</div>

<div class="box">content</div>
Community
  • 1
  • 1
he8us
  • 69
  • 7
1

Azim's answer sums it up. But since some new developers don't understand how ternary operations work, you can achieve it with the old fashioned if else statement as well.

HTML:

<div class="showlink">click</div>
<div class="box">content</div>

jQuery:

$(".box").hide();
$(".showlink").click(function(){
    $(".box").toggle();
  if($(".showlink").click){
    $(".showlink").text("click again");
  } if ($(".box").css("display") == "none") {
    $(".showlink").text("click");
  }
});

Working demo

Ray
  • 9,184
  • 3
  • 27
  • 44