2

I have an anchor tag which when clicked seems to scroll to the top of the screen.

I am using onclick and sending a model property to the function.

How can i prevent scrolling to top.

I have tried entering the href as javascript:void(0); and tried returning false.

<a href="javascript:void(0);" onclick="GetUsers('@(user.Code)');"><img ... /></a>

function GetUsers(Code) {
    $.ajax({
        ...
    });                                             
}

Update

Tried debugging it and it doesn't get to this line.

 var user = $(this).data('user-code'); 

Also no errors on page.

$.ajax({
            type: "GET",
            url: "/Admin/GetUsers/",
            data: { "User": user},
            success: function (data, textStatus) { ...

Doesn't get to this point...

Update

Now getting all the information, although the scrolling is still an issue. The prevent default doesn't seem to make any difference.

PhilGibson
  • 72
  • 8

2 Answers2

2

To do this you need to stop the default action of the button. Firstly, use jQuery to attach your events instead of the outdated on attributes:

<a href="#" class="myLink" data-user-code="@(user.Code)"><img /></a>

Then in your jQuery event handler, you can use preventDefault on the passed event:

$('.myLink').click(function(e) {
    e.preventDefault();
    var user = $(this).data('user-code');
    $.ajax({
        // ajax settings...
    }); 
});

I used a data attribute on the element to hold the parameter which I'm guessing is required in your AJAX call.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

A way to stop the scrolling without adding to javascript would be to set the href to an anchor with an ID that is not on the page, for example -

<a href="#!" onclick="GetUsers('@(user.Code)');"><img ... /></a>

Would work as it is unlikely that you will have an element with the name '!' on your page.

Mael
  • 86
  • 1