Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery : Append querystring to all links

I would like to append a query string onto all dynamic links within a page - to fix a bug in a old release - is this possible?

Any ideas?

like image 703
Dancer Avatar asked Jul 17 '12 15:07

Dancer


2 Answers

Something like this?

var querystring = 'myquerystringtoadd';

$('a').each(function() {
    var href = $(this).attr('href');

    if (href) {
        href += (href.match(/\?/) ? '&' : '?') + querystring;
        $(this).attr('href', href);
    }
});

Working example.

like image 195
Paul Fleming Avatar answered Nov 13 '22 02:11

Paul Fleming


This solution with native javascript :

var querystring = 'yourQueryStringHere=;-)';

document.addEventListener('click', function (e) {

    var x = e.originalTarget;
    if (x.nodeName === 'A') {

        var href = x.getAttribute('href');

        if(href) {
            href += (/\?/.test(href) ? '&' : '?') + querystring;
            x.setAttribute('href', href);
        }
    }

}, false);
like image 24
Rabih Avatar answered Nov 13 '22 02:11

Rabih