Archive for April, 2018

Different ways to display Chrome logging entries

Wednesday, April 25th, 2018

When I develop in the web, there are plenty of times that I want to see information about where I am in the program or what is going on in the Javascript when I load the page. I use the Console to watch updates but it can be difficult to read when you have possibly hundreds of log statements.
Usually you can just use the standard console.log function:

> console.log("Some information");
Some information
or 

> console.debug("Some information");
Some information

or 

> console.info("Some information");
Some information

You also get the line number and file that the output comes from in the console.

But did you know that you can use the following:

console.clear()
console.error(object)
console.table(array)
console.warn()

Let’s say you want to clear the current console. You can place in your code, or use it within the console itself.

console.clear();

Or you can get color coded lines with the warn or error functions:

> console.warn("This is a warning");
► This is a warning
> console.error("Error: Danger");
Error: Danger
And if you need to display an array that and want a better layout use console.table():
> console.table(['a','b','c']);
(index) Value
0 “a”
1 “b”
2 “c”
► Array(3)

Kick off Chrome Debugging

Thursday, April 12th, 2018

I was talking to a friend of mine on the phone the other day and we were talking about how debugging in Chrome was sometimes frustrating. We both had some ideas on how that could have been made better for each of us.

While you can load your page, find the line of code, and add a set of breakpoints. He let me know kicking off the debugger in a certain part of your code just by adding the following line of code where you want the code to stop:

debugger;

Once this brings up the debugging window, this behaves like a breakpoint and stops execution. Now you can see the value of your variables, or you can step through the rest of your code line by line.

My next post will talk about the different kind of console logging functions that are availabole.

Using Javascript to add elements to a page with class or ID

Wednesday, April 11th, 2018

There are times you might want to dynamically generate elements on a page and add classes to style them. You can create elements with ids and/or classes with plain Javascript with the following commands:

var newElement = document.createElement(“div”);
//to add a class:
newElement.setAttribute(“class”, “card”);
//to add an id
newElement.setAttribute(“id”, “id_name”);
//to add it to the body:
document.body.appendChild(newElement);
// or to add it to some element:
document.getElementById(“card-box”).appendChild(newElement);

You could also create the string for an element and attach it to the content of a div.

var newElement = '<div id="id_name" class="card">Some Content</div>';
 // This will replace the contents with your new element. 
document.body.innerHTML = newElement;