Stopping the page from jumping to the top on an href click

Given the following markup how would I stop the page from jumping to the top when the link is clicked:

<span id="newlikes"><a onclick="TracLikes('CurrentUser.UserName',<%#Eval("DocumentID")%>); return true" href="/KeepingTrac.aspx?DocID=<%# Eval("DocumentID") %>"><%#GetBlogLikesCount(Eval<int>("DocumentID"))%>  Likes</a></span></span>

Open in new window


The onclick calls a jquery passing the two parameters and returns a count.  The href stays on the same page but appends a unique docid so that each "likes" is unique; otherwise the Jquery fires for one click and no other.  

This a rework of a discussion I had awhile back

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28681380.html

This is the JQuery

function TracLikes(UserName,DocumentID) {
  
  var myuser = UserName;
  var mydoc = DocumentID;
   
  $.ajax({
             type: "POST",
             url: "/CMSPages/WebService.asmx/InsertLikes",
             async: true,
            data: JSON.stringify({ UserName: myuser, DocumentID: mydoc }),
             //data: JSON.stringify({
                 //UserName: $(this).data("UserName"),
                 //DocumentID: $(this).data("blogposttitle")
             //}),
             contentType: "application/json",
             success: function(data) {
                $(this).text(data.d + ' Likes');
             },
             error: function(XMLHttpRequest, textStatus, errorThrown) {
                 console.log(errorThrown);
             }
         });
   
}

Open in new window


This is the resulting page is attached.  Each time a "Likes" link is clicked the page jumps to the top.  Since this is the Home Page I must correct.
LinksMisbehaving
Any help is greatly appreciated.
sherbug1015Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mukesh YadavFull Stack DeveloperCommented:
Replace
return true

Open in new window

to
return false;

Open in new window


in this code
<span id="newlikes"><a onclick="TracLikes('CurrentUser.UserName',<%#Eval("DocumentID")%>); return true" href="/KeepingTrac.aspx?DocID=<%# Eval("DocumentID") %>"><%#GetBlogLikesCount(Eval<int>("DocumentID"))%>  Likes</a></span></span>

Open in new window

0
sherbug1015Author Commented:
When I set return to false, I don't get a count back unless I refresh the page.  For example the first blog has 38 likes.  If I click on the likes, I should immediately see 39 likes.  The return false stops the value from being returned to the onclick.    When I look at the click using Fiddler I see the return value from the service, just not making it to the page when return is false

Any other suggestions
0
hieloCommented:
At the end of the onclick use return false; and set href="#"
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

sherbug1015Author Commented:
hielo - I cannot use any of these methods as I need a return value and return false prevents the value from returning to the onclick.  Using href="#" does not give me a unique identifier for each like clicked and the jQuery fires on the first click only.  I have done due diligence and have tried all the obvious methods, but without success.
0
Mukesh YadavFull Stack DeveloperCommented:
Ok can you share code ot TracLikes function or add return false to this function at bottom and remove return true from onClick event handler.
0
Michel PlungjanIT ExpertCommented:
So let's try this from the top

You need to call

/KeepingTrac.aspx?DocID=<%# Eval("DocumentID") %>

AND execute

TracLikes('CurrentUser.UserName',<%#Eval("DocumentID")%>)

There are errors in the code anyway. You cannot use $(this) in the success.

So let's rebuild the link - I am not sure where you get CurrentUser.UserName, but you can change that I am sure:

<a class="likeLink" data-username="CurrentUser.UserName" data-docid="<%#Eval("DocumentID")%>" 
href="/KeepingTrac.aspx?DocID=<%# Eval("DocumentID") %>"><%#GetBlogLikesCount(Eval<int>("DocumentID"))%>  Likes</a>

Open in new window


Then the jQuery could be

$(function() {
  $(".likeLink").on("click",function(e) {
    e.preventDefault(); // cancel link and scroll
    var data: JSON.stringify({ UserName: $(this).data("username"), DocumentID: $(this).data("docid") });
    var $link = $(this);
    $.get($(this).attr("href"),function() { // first GET the link (I would personally chain on the server
      $.ajax({ // then POST the like
             type: "POST",
             url: "/CMSPages/WebService.asmx/InsertLikes",
             data: data,
             contentType: "application/json",
             success: function(data) {
                $link.text(data.d + ' Likes');
             },
             error: function(XMLHttpRequest, textStatus, errorThrown) {
                 console.log(errorThrown);
             }
       }); // $ajax
     }); // $.get
  });// click
}); // load

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
When I set return to false, I don't get a count back unless I refresh the page.  For example the first blog has 38 likes.  If I click on the likes, I should immediately see 39 likes.  The return false stops the value from being returned to the onclick.    When I look at the click using Fiddler I see the return value from the service, just not making it to the page when return is false

I think you need to understand what is happening here.

Unless you put the return false in as has been suggested by other experts in this post the default behaviour for the <a> element is going to fire which is to navigate to /KeepingTrac.aspx?DocID=<%# Eval("DocumentID") %>

This will by default refresh the likes count because the page is being refreshed. It will also make the page "jump" to the top - because it is a reload of the page.

If your count does not update when return false is used then there is something wrong with your code that updates the count - because the fact it does not update means that the return false has done exactly what it was supposed to do which is prevent the default behaviour of the <a> element.

Therefore the first post in this thread is correct - you have to put return false to prevent the default click behaviour.

The next question is why your count does not update so lets look at that  

In your success function you have this line

$(this).text(data.d + ' Likes');

Open in new window


In this context $(this) does not refer to the element that invoked the click. Try changing this line to

$('#newlikes a').text(data.d + ' Likes');

Open in new window

0
sherbug1015Author Commented:
Thanks everyone for your help.  I am still trying to get your solutions to work.  So far, not having any luck, but will get back after I try a bit more.

Thanks
0
skijCommented:
I don't see a purpose for the href.  Also, I see an extra closing </span> tag that does not match an opening <span> tag.

Try taking out the href and modifying the jQuery code as the others have suggested.

<span id="newlikes"><a onclick="TracLikes('CurrentUser.UserName',<%#Eval("DocumentID")%>)"><%#GetBlogLikesCount(Eval<int>("DocumentID"))%> Likes</a></span>

Open in new window

function TracLikes(UserName,DocumentID) {
  
  var myuser = UserName;
  var mydoc = DocumentID;
   
  $.ajax({
             type: "POST",
             url: "/CMSPages/WebService.asmx/InsertLikes",
             async: true,
            data: JSON.stringify({ UserName: myuser, DocumentID: mydoc }),
             //data: JSON.stringify({
                 //UserName: $(this).data("UserName"),
                 //DocumentID: $(this).data("blogposttitle")
             //}),
             contentType: "application/json",
             success: function(data) {
                $('#newlikes a').text(data.d + ' Likes');
             },
             error: function(XMLHttpRequest, textStatus, errorThrown) {
                 console.log(errorThrown);
             }
         });
   
}

Open in new window

0
Michel PlungjanIT ExpertCommented:
The href gives the free pointer AND retains some functionality even when JS is turned off or blocked
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.