Search code examples
javascriptjqueryhtmlclasshref

Simple jquery/javascript switch href


I have this link:

<div name="top">
  <!-- some code -->
  <a class="myLinkToTop" href="#bot">Click</a>
  <!-- some code -->
<div name="bot">

I wish to change the href attribute when it's clicked. I'm using this script:

 <script>
   $(".myLinkToTop").click(function(){
     $("a.myLinkToTop").attr("href","#top");
   });
 </script>

But I have 2 problems:

  • When I click the link its href changes, but the action sends me to the #top, instead of #bot.
  • After that, I want the href to switch between #top and #bot. I don't know how to do that so I was thinking about changing my class value with "toggleclass()" but I don't think this is the best use for my problem.

Solution

  • This will move to the current href on link and then change it:

    $(".myLinkToTop").click(function(e){ 
        e.preventDefault();
        window.location.href = this.href;
        this.href = this.hash === "#top" ? "#bot" : "#top";
     });