JQuery: prohibiting window scrolling after clicking a link

I have two links that hide other information to users on the main page. When you click on one link, new information appears on the screen. The problem is that when I click on any of the links, the window returns to the top of the page. I would like to prevent this behavior as it is annoying.

Here is the link code

<div align="right" id="ajaxIncomingMail"><a href="#" class="incomingMail">Incoming Mail</a></div><div id="ajaxOutgoingMail"><h5><a href="#" class="outgoingMail">Outgoing Mail</a></h5></div> 

and here is the code for jquery:

  $(function(){ $("a.incomingMail").click(function(e){ e.preventDefault(); $("#ajaxMailShowContentOutbox").hide(); $("#ajaxMailShowContentInbox").fadeIn("slow"); }); $("a.outgoingMail").click(function(e){ e.preventDefault(); $("#ajaxMailShowContentInbox").hide(); $("#ajaxMailShowContentOutbox").fadeIn("slow"); }); return false; }); 

Here I use preventDefault () and it still does not work !? I also tried returning false, but that didn't work either. I don't know if this matters, but the information that is presented is pulled with php from db. How can I make a scroll stop when I click on a link?

+4
source share
3 answers

Should return false; be in the actual jQuery click event, and not outside?

change

  $(function(){ $("a.incomingMail").click(function(e){ e.preventDefault(); $("#ajaxMailShowContentOutbox").hide(); $("#ajaxMailShowContentInbox").fadeIn("slow"); return false; }); $("a.outgoingMail").click(function(e){ e.preventDefault(); $("#ajaxMailShowContentInbox").hide(); $("#ajaxMailShowContentOutbox").fadeIn("slow"); return false; }); }); 
+10
source

you may have href = '#' in the a tag, change it to href = '###' and it should stop scrolling.

+3
source

You can try:

 $("a.incomingMail").live("click", function(e) { e.preventDefault(); $("#ajaxMailShowContentOutbox").hide(); $("#ajaxMailShowContentInbox").fadeIn("slow"); }); 

and

 $("a.outgoingMail").live("click", function(e) { e.preventDefault(); $("#ajaxMailShowContentInbox").hide(); $("#ajaxMailShowContentOutbox").fadeIn("slow"); }); 

instead of .click, if your information is retrieved from the database, because linking the click event handler to your links with .click () will only apply the event handler to the elements already loaded on the page and not the elements that are later loaded from your database .

+2
source

Source: https://habr.com/ru/post/1341065/


All Articles