-1

What I want to achieve is to be able to click text on screen and then the text I clicked changes to another word.

For example :

if I click 'view as list' I want it to change to 'Thumbnails'

Here is my attempt below:

html code:

<div class="page-intro">
    <h2>Artists</h2>
    <h2 class="thumb-to-list">View As List</h2>
</div>

css code:

.page-intro {
  background: orange;
}

.page-intro h2 {
  font-weight: normal;
  display: inline-block;
}

.thumb-to-list {
  float: right;
}

Here is my attempt at code but it's not working:

$('.thumb-to-list').toggle(function() {
    $('.thumb-to-list').text('View As Thumbnails');
}, function() {
    $('.thumb-to-list').text('View As List');
});
War10ck
  • 12,387
  • 7
  • 41
  • 54

3 Answers3

2

There is no need to use on() function, because Your DOM doesn't changes by changing it's values/text. You should just use click() function.

$('.thumb-to-list').click(function() {
    $(this).text('View As Thumbnails');
}
Jazi
  • 6,569
  • 13
  • 60
  • 92
  • 2
    I know what is the difference between those function. There is no need to use .on() in here. – Jazi May 13 '15 at 13:58
  • .click is old and will be deprecated eventually. People stopped using that ages ago. Go learn some jquery – Tech Savant May 13 '15 at 13:58
  • Source about that info? – Jazi May 13 '15 at 13:59
  • @NotoriousPet0 Could be wrong but I'm pretty sure based on the official docs that `.click()` uses `.on()` internally. Here's a snippet from the docs: _"This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third."_ **Source**: [`.click()`](http://api.jquery.com/click/) That being said I tend to use `.on()` simply because I like consistency between the attaching of all my event handlers. As far as I can see though based on the docs, it's perfectly acceptable either way. – War10ck May 13 '15 at 14:09
  • 1
    OK, I didn't realize they had changed it. They must have done that recently. They used to be different. Good to know. You learn something new every day. – Tech Savant May 13 '15 at 14:11
2

You can use directly the click event :

$(".thumb-to-list").click(function() {
    if ($(this).text() == "View As Thumbnails")
       $(this).text("View As List")
    else
       $(this).text("View As Thumbnails");
});
jmgross
  • 2,306
  • 1
  • 20
  • 24
2

You need to bind your mouse click to an event

$('.thumb-to-list').on('click', function() {
  if ($(this).text() == "View As List") {
    $(this).html('View As Thumbnails');
  } else {
    $(this).html('View As List');
  }
});
.page-intro {
  background: orange;
}
.page-intro h2 {
  font-weight: normal;
  display: inline-block;
}
.thumb-to-list {
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page-intro">
  <h2>Artists</h2>
  <h2 class="thumb-to-list">View As List</h2>
</div>
Janaka Dombawela
  • 1,337
  • 4
  • 26
  • 49