anatp_123 anatp_123 - 27 days ago 15
jQuery Question

How to get specific text when clicking on button?

I want to get the specific text that is shown and tweet it out.

http://codepen.io/anon/pen/mOeXVM

below its my code:

function tweet () {
var phrase = $(this).text();
alert(phrase);
// var phrase = document.getElementsByClassName('panel-body')[0];

var tweetUrl = 'https://twitter.com/share?text=' +
encodeURIComponent(phrase) ;

window.open(tweetUrl);
}

Answer

By using var phrase= $(this).text(), you are getting the 'Text' of the clicked button since it's the element that called the function. Instead you need to get the text of the panel that's currently visible. The following jQuery should do the trick

function tweet () {
  var newarr = $('.panel-body:visible').text();
  alert(newarr);
  //var phrase = document.getElementsByClassName('panel-body')[0];

  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(newarr) ;

  window.open(tweetUrl);
}