jQuery click event on view load

This is how to fire jQuery event on ASP.NET Core MVC view load;

HTML

<div class="container">
    <div class="nav">
        <ul id="menu">
            <li id="link1"><a href="#">Topic One</a></li>
            <li id="link2"><a href="#">Topic Two</a></li>
            <li id="link3"><a href="#">Topic Three</a></li>
        </ul>
    </div>
    <div class="main">
        <div id="page1" class="content">
            <h1>Page 1</h1>
            <p>First section of content.</p>
        </div>
        <div id="page2" class="content">
            <h1>Page 2</h1>
            <p>Second section of content</p>
        </div>
        <div id="page3" class="content">
            <h1>Page 3</h1>
            <p>Third section of content.</p>
        </div>
    </div>
</div>

jQuery

<script type="text/javascript">
    $('#menu a').click(function (e) {
        hideContentDivs();
        var tmp_div = $(this).parent().index();
        $('.main div').eq(tmp_div).show();
    });

    function hideContentDivs() {
        $('.main div').each(function () {
            $(this).hide();
        });
    }
    hideContentDivs();

    //fire this event on view load
    $(function () {
        $('#menu li a:first').click();
    });

</script>

This function does the auto click on view load;

$(function () {
    $('#menu li a:first').click();
});

Resources;

https://forum.jquery.com/topic/menu-links-show-hide-content-in-another-div

https://stackoverflow.com/questions/7468950/execute-click-event-on-load

Load Bootstrap tabs dynamically

Need Bootstrap tabs, but with dynamic content? Use this JS to fetch the content before showing the tab. Works for in-content links as well.

//the reason for the odd-looking selector is to listen for the click event
// on links that don't even exist yet - i.e. are loaded from the server.
$('#tabs').on('click','.tablink,#prodTabs a',function (e) {
    e.preventDefault();
    var url = $(this).attr("data-url");

    if (typeof url !== "undefined") {
        var pane = $(this), href = this.hash;

        // ajax load from data-url
        $(href).load(url,function(result){      
            pane.tab('show');
        });
    } else {
        $(this).tab('show');
    }
});

Read more here

Uncaught Reference Error: jQuery is not defined

You are getting this error in your ASP.NET Core application. Your Layout page has the proper reference;

    <script src="~/lib/jquery/dist/jquery.js"></script>

When you try to navigate to your content page where you want to use jQuery;

$(function () {
      alert("Test");

You see above error. Dammit. What’s wrong. jQuery library is referenced in Layout page and suppose to work in content page.

Chances are that you have not defined script section in your Layout page.

@section Scripts {
  <script>
    $(function () {
      alert("Test"); 
    });
  </script>
}

This will solve the problem and pain will go away.