Chrismo16
Chrismo16

Reputation: 17

Replacing text of an element with different values depending on what element is clicked (simplifying code)

I have the following code and 8 different .overlay elements. I would like to change the text of #target with a unique value depending on which .overlay I click. It works if I use 8 of these and use unique IDs instead of the .overlay class as my selector but I would prefer to make it as clean as possible, maybe using a var in place of "some text"

$('.overlay').on("click",function(){
    $('#target').animate({'opacity': 0}, 1000, function () {
        $(this).text("some text");
    }).animate({'opacity': 1}, 1000);
});

Upvotes: 1

Views: 34

Answers (2)

Rick Calder
Rick Calder

Reputation: 18695

Set a title attribute on the overlays then do this:

$('.overlay').on("click",function(){
    var text = $(this).attr("title");
    $('#target').animate({'opacity': 0}, 1000, function () {
        $(this).text(text);
    }).animate({'opacity': 1}, 1000);
});

Demo http://jsfiddle.net/calder12/PJTre/1

Upvotes: 1

jjnguy
jjnguy

Reputation: 138874

You could add a data attr on the .overlay item and use that value. It might look something like this:

$('.overlay').on("click",function(){
    var $clicked = $(this);
    $('#target').animate({'opacity': 0}, 1000, function () {
        $(this).text($clicked.data('text'));
    }).animate({'opacity': 1}, 1000);
});

Your html would look like:

<div class="overlay" data-text="some-text"></div>

Upvotes: 1

Related Questions