Day 4: Cloning Elements and Data Attributes

Thursday, June 29, 2017

Lecture Videos

Morning:

Playlist | Day 4, Part 1

Afternoon:

Playlist | Day 4, Part 1

Topics

DOM Manipulation

Array methods

Foundation

Examples

Data Attributes

HTML5 gave us a way to save extra information on a standard HTML Element via the data-* attributes. Basically, you can add any arbitrary information you want, prefixing the name of the attribute with data-. This data is then accessible through JavaScript via the someElement.dataset object, or through CSS via attr(data-*).



<div
  id="my-div"
  data-name="Awesome div"
  data-id="div-1234"
  data-color="blue"
  data-marshmallows="yummy">
</div>




const myDiv = document.querySelector('#my-div')

myDiv.dataset.name            // "Awesome div"
myDiv.dataset.data-id         // "div-1234"
myDiv.dataset.color           // "blue"
myDiv.dataset.marshmallows    // "yummy"




#my-div {
  background-color: attr(data-color);
}

div[data-id='div-1234'] {
  height: 400px;
  width: 400px;
}


.cloneNode

Sometimes it may be easier to clone an existing node rather than build an entirely new one, especially if the markup is complex. In our ‘Michael Bay-watch’ project, we kept a hidden li in the DOM that we cloned every time we needed to render a new list item.



<li class="flick grid-x align-middle template">
  <span class="flick-name cell auto">sdfkjhgds</span>
  <span class="actions button-group cell shrink">
    <button class="fav button warning">fav</button>
    <button class="remove button alert">del</button>
  </span>
</li>




/* hides any 'li' with a 'template' class */
li.template {
  display: none;
}




const list = document.querySelector('ul')
const templateItem = document.querySelector('li.template')

// Make a copy of the templateItem
// Pass 'true' as an argument to clone all children as well
const newItem = templateItem.cloneNode(true)

// remove 'template' class so it is no longer hidden
newItem.classList.remove('template')

list.appendChild(newItem)


Array methods



const ary = [1, 2, 3, 4, 5]

ary.unshift(0)

console.log(ary)    // [0, 1, 2, 3, 4, 5]

ary.shift()         // 0

console.log(ary)    // [1, 2, 3, 4, 5]

ary.reverse()

console.log(ary)    // [5, 4, 3, 2, 1]


Presentations

Projects

Michael Bay-watch: Morning | Afternoon

Homework

  • Finish implementing move up and move down.

Bonus Credit

  • Allow users to edit the names of existing flicks. Wouldn’t it be nice if we could make that span’s content editable?

Super Mega Bonus Credit

  • Persist the data using localStorage. When you refresh the page, your flicks should still be there.

Super Mega Bonus Credit Hyper Fighting

  • Allow users to filter the list of flicks.