Search code examples
asp.net-mvcjquerypreventdefault

Calling preventDefault on DOM element


I am currently in the process of creating an MVC4 web application, and I seem to have run into a weird issue. I have created a unordered list with some list items in it, and their respective anchor tags, in which I am going to be able to click, that will return the respective /CONTROLLER/ACTION view.

    <div>
        <ul>
            <li>
                <a class="ajax" href="/Test/One"></a>
            </li>
            <li>
                <a class="ajax" href="/Test/Two"></a>
            </li>
            <li>
                <a class="ajax" href="/Test/Three"></a>
            </li>
            <li>
                <a class="ajax" href="/Test/Four"></a>
            </li>
        </ul>
   </div>

   <div id="body">
   </div>

I have then created some jQuery to call when you click either of the anchor tags, looking for a class of "ajax", and if you are to click the anchor tag, it will then run another function called GetContent, passing through the HREF value of the anchor tag, which will be used as the path for the ajax call.

$(document).ready(function () {
    $(".ajax").click(function () {
        var path = $(this).attr("href");
        GetContent(path);
    });
});

function GetContent(path) {

    $.ajax({
        url: path,
        type: 'POST',
        async: false,
        success: function (result) {
            $("#body").html(result);
        }
    });
}

I have heard of a function you can call, called preventDefault I believe. I am finding that I am not sure when to call this preventDefault to override the click of the anchor tag.

I did try placing it into a couple of places, but with no luck... I am finding at the moment I am able to click any of the anchor tags, and the default action occurs, it simply returns the whole website with the new view loaded. However if I open up the console in google chrome developer tools, and call the function GetContent, passing through the path I am expecting, it will then call the function, return the ajax, and update my web page.

If someone is able to point out where I am supposed to call the preventDefault function that would be great.


Solution

  • preventDefault is a method of event object. You get the reference to event object as first param of the click event handler…

    $(".ajax").click(function (event) {
        var path = $(this).attr("href");
        GetContent(path);
        event.preventDefault();
    });