Phill Healey
Phill Healey

Reputation: 3180

Trigger jQuery function on page load

I've created some jQuery that take a value from a one of several buttons and then via ajax loads the corresponding custom post types. Each button represents a category that the posts are associated with.

This is as follows:

jQuery(function ($){
    jQuery('.btn').on('click', function(e){
        e.preventDefault();
        $.ajax({
            url:'/wp-admin/admin-ajax.php',
            data:('categoryfilter=' + $(this).val() + '&action=projects'),   //filter.serialize(),
            type:'POST', 
            beforeSend:function(xhr){
            },
            success:function(data){
                    $('#somediv').first().after(data);
            }
        });
        return false;
    });
}); 

The html for the "filter" buttons is:

<div id="myBtnContainer">
<form  method="POST" id="filter">
  <button class="btn active" value="all"> Show all</button>
  <button class="btn" value='Business' />Business</button>
  <button class="btn" value="Charity"> Charity</button>
  <button class="btn" value="education-research"> Education / Research</button>
  <button class="btn" value="Heritage"> Heritage</button>
  <button class="btn" value="health-environment"> Health / Environment</button>
</form>
</div>

This all works great, however I need to load some content when the page loads. No records/posts are displayed until the ajax is fired on the click of one of the filter buttons.

I've tried giving the onclick function a name but, I can't call it - eg:

jQuery(document).ready(function($){
//jQuery(function ($){

        alert ("test text");
        loadProjects();

    jQuery('.btn').on('click', function loadProjects(e){
    //jQuery('.btn').on('click', function(e){

How can I convert my current code to make it so that I can load some default content on page load?

Upvotes: 0

Views: 350

Answers (1)

Muhammad Saud
Muhammad Saud

Reputation: 354

You should be able to trigger the click event callback by doing:

jQuery(function ($){
    jQuery('.btn').on('click', function(e){
        e.preventDefault();
        $.ajax({
            url:'/wp-admin/admin-ajax.php',
            data:('categoryfilter=' + $(this).val() + '&action=projects'),   //filter.serialize(),
            type:'POST', 
            beforeSend:function(xhr){
            },
            success:function(data){
                    $('#somediv').first().after(data);
            }
        });
        return false;
    });

    //trigger first btn's click event
    $('#filter .btn.active').trigger('click');
});

Upvotes: 3

Related Questions