Monday, November 25, 2013

Who will console(.log) me?

I have to remember how powerful console.log is. 

Right now I have some of the following code in my rails app


-->new.html.erb
<div class="col-sm-9 qwerty">
        <div class="row">
          <button class="col-xs-3 btn btn-default" data-num="1">1</button>
.
.
.

<div class="operations">
          <div class="row">
            <button class="col-xs-6 col-xs-offset-6 btn btn-default" data-operation="+">+</button>
          </div>
.
.
.
How would I test to see if I am traversing the DOM correctly? In the past (as in earlier today) I would have just written my code and hoped for the best. 

There is a better way- at least until my coding skillz are up to snuff:

-->calculators.js
###

$(function() {
console.log($(".qwerty"))
// or console.log($(".qwerty").children())
});
###
Snap, it worked. Now, what will we get back with "this"? 

$(".qwerty").on("click", "button", function(event){
      console.log(this);

Looks like the html element as we wanted when we click on the "1" button (on the console we get: <button class="col-xs-3 btn btn-default" data-num="1">1</button>)

###

Know what would be SICK? If we could get that data-num. Afterall, after pushing one of those buttons we want to "retain" a value. 

adding: console.log(this.getAttribute("data-num")); 
done, shows we can indeed get that data-num value

###

what about these?

console.log(event);  ~>
console.log(event.currentTarget); ~>
console.log(this); ~>
console.log(this.getAttribute("data-num")); ~> 0
console.log(this.getAttribute("class")); ~>

console.log($(this).data("num")); ~>0


1 comment:

  1. Console.log is a great method for demystifying your code and figuring out what's going on. In fact it is one of the few tools we have for debugging JS.

    ReplyDelete