fix js error and reorganise the js more efficiently