Rearranged code and introduced more variables instead of direct access to jquery