2

Hi friends i am trying to change the Data-caption of a in dynamic mode.

$("#btnchange").click(function(){
    var newanchor=  $(".fancybox a");
    newanchor.attr('caption', 'i am new caption');
});

When I clicked on the image to open it in third party plugin, tool called(fancybox), it's caption is not displaying.

But when I tried to add data caption by default it like:

<a id='a1' class="fancybox" data-caption='hey' 
 href="http://farm8.staticflickr.com/7171/6417719753_374653e28c_b.jpg">
    <img src="http://farm8.staticflickr.com/7171/6417719753_374653e28c_m.jpg" alt=""/>
</a>

Then it is showing perfectly. See my fiddle:

http://jsfiddle.net/RyTcS/401/

Alex VII
  • 930
  • 6
  • 25
user3860465
  • 55
  • 2
  • 9

3 Answers3

1

Try to use .data() instead of .attr(),

newanchor.data('caption', 'i am new caption');

DEMO

And as well as your selector should be .fancybox instead of .fancybox a

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

You have the wrong selector, Your current selector will chek for the anchor inside the class fancybox .So change the code like this,

 $("#btnchange").click(function () {
      $("a.fancybox").attr("data-caption", "i am new caption");

 });

Demo

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • 2
    attr not working ...as per the answers we can see ..it is 'data' – user3860465 Jul 21 '14 at 12:13
  • @user3860465 "attr not working". How can you say that its not working? Its working fine. – Anoop Joshi P Jul 21 '14 at 12:16
  • @AnoopJoshi : what the OP means is that you could use the `attr()` method to set a **new** `data-caption` attribute but **NOT** to change an existing one. If the second, you should rather use the `.data(key,value)` format as suggested by Raja http://jsfiddle.net/9Wwyt/ – JFK Jul 21 '14 at 15:39
  • @JFK Can you check this fiddle? http://jsfiddle.net/9Wwyt/1/. Here the value is changing by using .attr() method – Anoop Joshi P Jul 22 '14 at 06:06
  • @AnoopJoshi : well, you are right, it does change. However, the issue is that fancybox's `title` doesn't get it unless you use `.data(key, value)`. Here an interesting discussion about the subject http://stackoverflow.com/a/7262427/1055987 – JFK Jul 22 '14 at 07:50
0
$(document).on('click', '#btnchange', function() {
    $('a.fancybox').data('caption', 'i am new caption');
});

You might find this example useful

martynas
  • 12,120
  • 3
  • 55
  • 60