Plastic
Plastic

Reputation: 10328

JQuery Retrive data-attribute from on click function

I have a div structure like this:

<div class='bar'>
    <div class='contents'>
        <div class='element' data-big='join'>JOIN ME</div>
        <div class='element' data-big='play'>PLAY ME</div>
        <div class='element' data-big='list'>GO TO LIST</div>
        <div class='element' data-big='chart'>GO TO TOP 10</div>
    </div>
</div>

How can I refer to their data attribute by onClick function?

I tried with

$(".bar .element").on('click', ()=> {
    alert($(this).data('big'));
});

But it always alert "undefined".

EDIT:

My assertion was bad from the beginning, I was using a lambda (or arrow) expression from the Typescript language. That makes the different meaning of the keyword "this".

the snippet:

$(".bar .element").on('click', function(){
    alert($(this).data('big'));
});

works as espected.

Upvotes: 2

Views: 2096

Answers (5)

PeterKA
PeterKA

Reputation: 24638

You do not have a .barra (as you had in your original JS -- $(".barra .element")) element in your HTML and you've not written the callback properly:

$(".bar .element").on('click', function() {
    alert($(this).data('big'));
});

    $(".bar .element").on('click', function() {
        alert($(this).data('big'));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='bar'>
    <div class='contents'>
        <div class='element' data-big='join'>JOIN ME</div>
        <div class='element' data-big='play'>PLAY ME</div>
        <div class='element' data-big='list'>GO TO LIST</div>
        <div class='element' data-big='chart'>GO TO TOP 10</div>
    </div>
</div>

Upvotes: 3

Fenton
Fenton

Reputation: 250942

In TypeScript, the arrow function expression (() =>) is used to preserve the lexical scope. This means that when you use this inside of an arrow function, it will refer to the same scope as using this outside of the function.

In your case, you want the function to run with the scope of the onclick event, not the lexical scope, so you should avoid using the arrow function and instead use function ().

Upvotes: 3

sasi
sasi

Reputation: 209

Here is the working solution:

jQuery:

$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

DEMO

Upvotes: 1

lem2802
lem2802

Reputation: 1162

you can use "id" to do it:

<div id='div1' class='element' data-big='join'>JOIN ME</div>

$("#div1").on('click', ()=> {
    alert($(this).data('big'));
});

Upvotes: 0

murli2308
murli2308

Reputation: 3004

you should change your function like below

$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

Upvotes: 3

Related Questions