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

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect