Puneet Kathar
Puneet Kathar

Reputation: 45

Add href to anchor tag on the n click

<section>
        <a **id="download"**  oncontextmenu="return false" > <svg ...
          </svg></a>
</section>
<script type="text/javascript">

The Code Below is just to get first 2 clicks.

$("#download").click(function(){
  $("#download").attr("oncontextmenu", "false");
});

$("#download").click(function({
  $("#download").attr("oncontextmenu", "false");
});

Here is the finalfunction which adds HREF on the 3rd click.

$("#download").click(finalfunction({
$("#download").attr("href", "<%= downloadLink %>");
});

</script>

But this code isn't working. Help me please.

Upvotes: 1

Views: 70

Answers (1)

mplungjan
mplungjan

Reputation: 178350

  1. IDs need to be unique. Use a class.

  2. Have ONE eventListener and count the clicks inside it

Try something like this

I added some debugging

$(".download").on("click",  e => {
  const anchor = e.currentTarget;
  let cnt = anchor.dataset.cnt;
  if (cnt === "2") {
    anchor.href = anchor.dataset.href;
    console.log("clicked 3 times")
  }  
  else {
    cnt++;
    anchor.dataset.cnt = cnt;
    $(".count",anchor).html(`Click ${3-cnt} more time${3-cnt === 1 ? "" : "s"}`)
    e.preventDefault()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <a class="download" href="#" data-cnt="0" data-href="...." class oncontextmenu="return false"><span class="count">Click 3 times</span> <svg ... </svg></a>
  <a class="download" href="#" data-cnt="0" data-href="...." class oncontextmenu="return false"><span class="count">Click 3 times</span> <svg ... </svg></a>
</section>

Upvotes: 2

Related Questions