2

I use NodeJs with Express and Handlebars.

I create a grid on the server and send the object to the client. The list contains cells having two properties, x position and y positon.

So I go for this code

$(document).ready(function() {
  var cells = $(".cell"); // get all cells
  
  $(cells).each(function(i, cell) {
    var currentCell = $(cell);
    var x = currentCell.data("xPos"); // get the xPos
    var y = currentCell.data("yPos"); // get the yPos
    
    currentCell.click(function() { // add a click event to each cell
      console.log(x + " | " + y);
    });
    
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

{{#each map}}
<div class="row">
  {{#each this}}

  <!-- <p>{{this.x}}</p> prints out a correct value! -->
  <!-- <p>{{this.y}}</p> prints out a correct value! -->

  <div class="cell" data-xPos={{this.x}} data-yPos={{this.y}}></div>
  {{/each}}
</div>
{{/each}}

When clicking on a cell the console logs

undefined | undefined

how can I set the data attribute? I just want to pass the information to the client script so I went for the data attribute.

An example DOM after building the page

DOM

1 Answer 1

1

The data attribute has to be

data-xpos={{this.x}} data-ypos={{this.y}}

So the full HTML would be

<div class="cell" data-xpos={{this.x}} data-ypos={{this.y}}></div>

and the JS

var x = currentCell.data("xpos");
var y = currentCell.data("ypos");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.