tomirons's avatar

Is there a way to simplify this?

I'm trying to reduce the amount of work here, cause this may be something I use across my application quite a lot.

<script>
    var page = 0;
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            } else {
                search($("input[name='search_query']").val(), page);
            }
        }
    });
    $(document).ready(function() {
        $(document).on('click', '.pagination a', function (e) {
            page = $(this).attr('href').split('page=')[1];
            search($("input[name='search_query']").val(), page);
            e.preventDefault();
        });
    });
    function search(query, page) {
        var box = $('.portlet-body#ajax');
        $.ajax({
            url: "{{ url( 'admin/management/members' ) }}",
            data: {
                'search_query' : query,
                'page' : page
            },
            success: function (response) {
                box.empty();
                box.html(response);
            },
            error: function (response) {
                console.log(response);
            }
        });
    }

    $("#search").keyup(function(){
        search($("input[name='search_query']").val(), page);
    });
</script>

I'm just trying to clean it up a bit, any help is much appreciated.

0 likes
2 replies
thefuzzy0ne's avatar

I'm not expert, but I think your code looks great!

However, if I were to really nit-pick, I'd say that the "else" part of your if-statement is redundant, since if the first part executes, the function returns false.

Also, I'd recommend you put your script inside a closure, to save potential clashes with other scripts.

Besides that, if that was code I had written, I'd be very, very happy with that.

willvincent's avatar

I would wrap the document ready around everything, and put it in a closure so that if you happen to use any other scripts that bind to $ in the future you don't run into problems..

(function($) {
  $(document).ready(function() {
  // rest of the code goes here
  });
})(jQuery);

Please or to participate in this conversation.