5

I have this html

<a data-overlay="Preparing First" href='#'>First link</a>
<a data-overlay="Preparing Second" href='#'>Second link</a>

And JS

$("[data-overlay]").click(function () {
        var text = $(this).val($(this).attr("data-overlay"));
        alert(text);
    });

When I do this, I got only OBJECT, where I got wrong?

Here is working fiddle

http://jsfiddle.net/sruq8kav/

What I need is to alert value of that custom attribute?

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Miomir Dancevic
  • 6,726
  • 15
  • 74
  • 142

2 Answers2

19

Because you're alerting the result of .val() (and I'm not sure why you're using it) which is a jQuery object - you simply want the attribute:

var text = $(this).attr("data-overlay")
alert(text);
tymeJV
  • 103,943
  • 14
  • 161
  • 157
5

In addition to tymeJV's answer, you can also get data- attributes in jQuery with the .data() method.

var text = $(this).data("overlay")
alert(text);

Be aware that doing so will return numbers, Booleans, or objects, if jQuery detects the data to be of that type. You can read more about that here.

Community
  • 1
  • 1
Scimonster
  • 32,893
  • 9
  • 77
  • 89