Razvan Zamfir
Razvan Zamfir

Reputation: 4614

custom attribute undefined

Inside THIS jsFiddle I have 2 buttons, each with a custom data-direction attribute:

 <div class="btn-group" id="controls">
  <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
  <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>

I am trying to console log the direction attribute upon clicking the buttons:

var updateCounter = function(){
  var direction = $(this).data("direction")
    if(direction === "left") {
    counter--;
  } else {
    counter++;
  }
  console.log(direction);
}

But what I get is undefined. Why?

Upvotes: 0

Views: 456

Answers (1)

gaetanoM
gaetanoM

Reputation: 42044

Change updateCounter function so that it takes one argument, just the element.

var numbers = [4, 9, 16, 25];
var counter = 0;
var updateCounter = function(ele){
  var direction = $(ele).data("direction")
  if(direction === "left") {
      counter--;
  } else {
      counter++;
  }
  console.log(counter);
  console.log(direction);
}

$('#numbers_wrapper').text(numbers[counter]);

$('#controls button').on('click', function(e){
  updateCounter(this);
  $('#numbers_wrapper').text(numbers[counter]);
});
.numbers {
    width: 34px;
    height: 34px;
    line-height: 34px;
    text-align: center;
    margin: 5px auto;
    border: 1px solid #286da9;
    background: #337ab7;
    color: #fff;
    border-radius: 2px;
}
.controls > div {
    display: inline-block;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div class="container">
    <div class="numbers text-center" id="numbers_wrapper"></div>
    <div class="controls text-center">
        <div class="btn-group" id="controls">
            <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
            <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
        </div>
    </div>
</div>

Upvotes: 1

Related Questions