0

I am looking for a code, which I can put inside a standard HTML href link - that, once the link is clicked, will immediately update a portion of the link in real-time.

Something like:

<a href="http://example.com/<?php code(); ?>/">Example</a>

Will at first print:

<a href="http://example.com/page1/">Example</a>

And so after it being clicked once, it'll instantly change to:

<a href="http://example.com/page1-clicked/">Example</a>

Anyone got anything simple up the sleeve for that?

Thanks!

Alex
  • 137
  • 1
  • 8

2 Answers2

3

First include JQuery

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>

Give your link an id

<a id="link" href="http://example.com/page1/">Example</a>

Use the link in your JQuery code

$(document).ready(function()    {
    $(document).on("click", "#link", function() {
        $(this).attr("href", "http://example.com/page1-clicked/");
    });
});

edit

I you want to do the same with many links give your link a class

<a class="link" href="http://example.com/page1/">Example</a>

Then change the JQuery code to

$(document).ready(function()    {
    $(document).on("click", ".link", function() {
        $(this).attr("href", "http://example.com/page1-clicked/");
    });
});
Wezy
  • 635
  • 1
  • 5
  • 14
  • Thank you. However I need a dynamic code that can replace a certain word in a link on a page where there are many different links that include that word - but only clicked once should be replaced... – Alex Sep 09 '14 at 08:49
  • Edited my answer to your comment – Wezy Sep 09 '14 at 09:48
  • I see, but if I need only change page1 to page1-clicked and not the whole link - how could I catch only that part? Also just to clarify please, it's not appending of the "-clicked", but switching the whole thing like so; ...com/123/ to ...com/xyz/. Thanks! – Alex Sep 09 '14 at 11:44
0

using JQuery's one event handler to change the link only once:

$(function () {
    $('a').one(function (event) {
        var elem = $(this);
        var before = elem.attr('href');
        var after = before + '-clicked/';
        elem.attr('href', after);
    })
});
gabber
  • 100
  • 7
  • for click once see also http://stackoverflow.com/questions/12885660/how-to-make-a-jquery-click-event-fire-only-on-first-click – gabber Sep 09 '14 at 08:55