-2

I have following JS function.

<script type="text/javascript">
    $(document).ready(function() {


        $("#fancybox-manual-a").click(function() {
            var imageName="facebook-default-no-profile-pic.jpg";
            var name="xxx";
                            var age="111";
            $.fancybox.open([{
                href : '<?php echo base_url().'public/';?>image,
                title : name+' '+age
            }]);
        });

    });
 </script>

I use this function as HREF link as follows and it works fine.

<a id="fancybox-manual-a" href="javascript:;">Click</a>

But I want to parse some arguments(values for name and age) when I call fancybox-manual-a function. How can I do ?

Malintha
  • 4,512
  • 9
  • 48
  • 82

1 Answers1

7

I suppose you want to set some values from the <a> element and pick them up in the click handler. You can attach data-* attributes on the element and fetch them using .data():

Append to your HTML like so:

<a id="fancybox-manual-a" href="#" data-foo="bar" data-baz="bam" data-some-long-name="someValue>Click</a>

Then use .data() to get them:

$("#fancybox-manual-a").click(function() {
  var data = $(this).data();

  var foo = data.foo;          //bar
  var baz = data.baz;          //bam
  var zee = data.someLongName; //someValue. Note the dash-separated to camelCase conversion

  ...
});
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • wow, is data-* a jquery feature? does if have to be called `data`? – Oleg Mikheev Dec 31 '13 at 05:52
  • No, it's an HTML5 feature. And yes, it has to start with *data-* in order to be valid markup. This also means that this answer is only valid if your document is an HTML5 document. – Ingo Bürk Dec 31 '13 at 05:53
  • @OlegMikheev You can actually put any arbitrarily named attribute, though it will trip off validators. jQuery's `.data()` just transparently goes through the ones with `data-*`, making it a handy function. – Joseph Dec 31 '13 at 05:56
  • `$(this).data()` is jquery function, does HTML5 provide any means to retrieve data without JS frameworks? – Oleg Mikheev Dec 31 '13 at 05:57
  • Is this a jquery function ? – Malintha Dec 31 '13 at 05:58
  • HTML is a markup language, speaking of data retrieval makes no sense within HTML. However, Javascript is perfectly capable of reading such attributes even without any library in the same way any other attribute can be read. data attributes is an *official* HTML5 feature. – Ingo Bürk Dec 31 '13 at 05:59
  • @OlegMikheev You can access the values directly, like `element['data-name']` or via `element.getAttribute('name')`. [Here's a post that explains which of the two to use](http://stackoverflow.com/q/3919291/575527). – Joseph Dec 31 '13 at 05:59