Basic Front-End Concepts

Get to know the common motions involved in front-end solutions.

ID's and Classes

The most important parts of reading jQuery code blocks are knowing what # and . refer to.

  • # – This tells jQuery that we are looking for an HTML element by its id.
  • . – This tells jQuery that we are looking for an HTML element by its class.

jQuery

var idElement = $('#element-id');
var classElement = $('.element-class');

HTML

<div id="element-id"></div> <!--corresponds to var idElement = $('#element-id');-->
<div class="element-class"></div> <!--corresponds to var classElement = $('.element-class');-->

Classes, Continued

When selecting by class, often times there are multiple elements with the same class name. You can access different elements using array notation, akin to classElement[0], classElement[1], etc.

Conversely, there should never be two elements in an HTML document with the same ID.

//Gather all elements with class 'element-class'
var classElements = $('.element-class');


//Set all elements of class 'element-class' to have red text color
for(var i = 0; i < classElements.length; i++){
  classElements[i].css('color','red');
}

Events

Another important concept in front-end development is the concept of events. Many new developers will run into a problem where none of their code works because it's pointing to elements that don't exist yet.


Wrapping events inside an initial event that occurs when the document's content is loaded solves this issue.

A Listener/Event Chain

Here, we are using JavaScript to add an event listener to the document. What event? DOMContentLoaded, of course. What do we do when when the event occurs? A function. What does this function do? Well, that's up to you, but in this case, we are using jQuery to add another event listener, this time to an HTML element with the ID button-element. When this listener's event ('click') occurs, we change its background color to blue.

document.addEventListener('DOMContentLoaded', function(){
$('#button-element').on('click', function(){
$('#button-element').css('background-color','blue');
});
});