Can't target data-position

I want to make an if statement where if this div id has this data-position value, do something, but it’s not working.

But if I change to if this div id has this data-class value, it’s working ok.

May I know why and how to solve it?

Here’s the codepen

Hi @nzrink1, I’m not quite sure what you mean – if I change data('class') back to data('position') I still get the alert each time I click the .next button.

Oops sorry, forgot to add id dp-next for the NEXT text.

Basically, it’s a navigation for the stack boxes. When I click NEXT, the next stack box data-position will become 1.

It works fine, but I want to add something if this div id has this data-position value. Check my updated codepen, now the alert popup is not working.

I made another codepen where instead of check the condition when the button clicked, I want it to check globally for the stack box data-position.

Basically, at default #define is under data-position=2 and I want to popup an alert when it is data-position=1, but it’s not working. If I change the selector to #discover which is data-position=1 by default, the alert works but only once.

It seems like the script only check the stack box data-position at initial page load only.

Ah ok… well I’m not familiar with that slider extension you’re using (looks like a custom solution?), but it seems that it indeed updates the data-position values; however, jQuery’s data() method doesn’t quite work the way you might expect as it stores those values internally, and doesn’t reflect subsequent changes to the attributes. From the docs:

Since jQuery 1.4.3, data-* attributes are used to initialize jQuery data. An element’s data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery).

So you have to check for the actual attribute value instead:

$('.next').on('click', function () {
  if ($('#discover').attr('data-position') === '1') {
    alert('Help Me');

Yes you have to do the check inside a click handler as in your 1st pen.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.