NewAtLearningThis
NewAtLearningThis

Reputation: 239

How to make a click event on a text JQUERY

      var $tweet = $('<div class = tweet></div>');
      $tweet.text('@' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);

I'm exploring JQuery and I'm generating tweets or messages by users. Is it possible to do a click event on a certain string on tweet.user? I assume not because it's not a jquery object. My line of thinking is that I have to make a separate $user object and reference the attribute of tweet.user and then I can have a click event on $user. Is that the right line of thinking? Just looking for some guidance!

Upvotes: 1

Views: 145

Answers (2)

M A Salman
M A Salman

Reputation: 3820

Use $().html() to include html having span with class then target it and set on click

let tweet={
  user:'Supercool',
  message:'Hey im cool 😎',
  created_at:'Just now'
}
$('.tweet')
.html(`
<span class="user">@${tweet.user} :  ${tweet.message} <br> ${tweet.created_at}</span>`
);

$('.tweet>.user').click(()=>console.log("Im clicked bro"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class = tweet></div>

Upvotes: 1

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

You can use .html() and .on()

var $tweet = $('<div class="tweet"></div>');
$tweet.html('<span class="tweet-user">@' + tweet.user + '</span>: ' + tweet.message + ' ' + tweet.created_at);

...

$(document).on("click", ".tweet-user", function(){ ... })

Upvotes: 1

Related Questions