Lena Luther
Lena Luther

Reputation: 23

jQuery Get Value of data Attribute

I tried several times now changing the code. But every time I get NaN ...

$(window).load(function() {
    $('.ytdl').click(function() {
        var v = $(this).data('href');
        var f = $(this).data('format');

        alert(v + f);

    });
});


<a data-href="KMU0tzLwhbE" data-format="1" rel="nofollow" target="_blank" class="ytdl">Download</a>

But why? I tried already also changing data to attr. But nothing of this is working.

Upvotes: 1

Views: 3462

Answers (1)

dyaa
dyaa

Reputation: 1450

Just change the load to ready

The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins. When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added. As of jQuery 3.0, jQuery ensures that an exception occuring in one handler does not prevent subsequently added handlers from executing. -- https://api.jquery.com/ready/

So here's a working demo https://jsfiddle.net/e89gh5Lk/

  • document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.
  • window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.

Upvotes: 2

Related Questions