UX Design and Development course

Prevent Default

http://jsbin.com/nuxucihe/2/edit

In this example we will walk through how to make an object in the UX fade into view. To start out, we need to create the outer click function that is bound to an element in the DOM.

$('.product').on('click', '.expand', function(event) {
    // ...
});

In the HTML (Jade) we will build out the following UI. .product is the outer wrapper of this module and we will use the a tag as the object we will bind the click event to.

The .comments block is what we will target for hiding and exposing based on the click.

.product
  p
    a.expand(href="http://apple.com")
      See comments

  .comments
    p. These are comments for people to see about the stuff they are trying to buy.
    p. These are comments for people to see about the stuff they are trying to buy.
    p. These are comments for people to see about the stuff they are trying to buy.

Our CSS:

.comments {
  display: none;
}

Ok, now that we have the base, let's add the awesome.

To make this work, we are going to use the this keyword and traverse the DOM to find the closest .product class and then find .comments within and apply a method to expose the content that is hidden in CSS.

$(this).closest('.product').find('.comments').fadeToggle();

This will work, but we have a problem ... the a tag is linked to something else? This left alone, when the user clicks this link it will take them to apple.com. Ok, so kill the URL, what if we just put in a #? In the example so far, the link is at the top and we haven't scrolled. Let's add more CSS:

.product {
  background-color: orange;
  height: 900px;
  padding-top: 400px;
}

Scroll and click ... what happens? To fix this we can use ...

event.preventDefault();

Beware - use this function appropriately as this kills all default functionality assigned to an element.

Play with code

JS Bin