Chain jquery operations and move final vars to upper scope