Skip to content Skip to sidebar Skip to footer

Add Parameter To Links On Page Using Jquery

How do I add let's say something like ajax=1 to all links on my page with jquery. I will also need to check if the url has existing parameters. for example http://example.com/index

Solution 1:

You could do something like this:

$(function() {
   $("a").attr('href', function(i, h) {
     return h + (h.indexOf('?') != -1 ? "&ajax=1" : "?ajax=1");
   });
});

On document.ready this looks at every <a>, looks at it's href, if it contains ? already it appends &ajax=1 if it doesn't, it appends ?ajax=1.

Solution 2:

Like this:

$(function() {
    $('a[href]').attr('href', function(index, href) {
        var param = "key=value";

        if (href.charAt(href.length - 1) === '?') //Very unlikelyreturn href + param;
        elseif (href.indexOf('?') > 0)
            return href + '&' + param;
        elsereturn href + '?' + param;
    });
})

Solution 3:

Here is a solution I put together for native Javascript, it supports existing query strings and anchors:

functionaddToQueryString(url, key, value) {
    var query = url.indexOf('?');
    var anchor = url.indexOf('#');
    if (query == url.length - 1) {
        // Strip any ? on the end of the URL
        url = url.substring(0, query);
        query = -1;
    }
    return (anchor > 0 ? url.substring(0, anchor) : url)
         + (query > 0 ? "&" + key + "=" + value : "?" + key + "=" + value)
         + (anchor > 0 ? url.substring(anchor) : "");
}

I've posted my existing tests on JSBin: http://jsbin.com/otapem/2/

Solution 4:

If you're interested in plugins, there's the jQuery Query String Object. This will allow you simple checking of parameters in the querystring, and if necessary the ability to add more, remove some, or edit others.

Solution 5:

Taking what is above, this is the best way to concatenate parameters to links.

Also avoid link with href like href="Javascript:YourFunction();"

$(function(){                                      
   var myRandom = getRandom();       
   $('a[href]').each(function(i){
        var currHref = $(this).attr("href");
        var isAfunction = currHref.substring(0,10);              
        if(isAfunction == "javascript"){                
            $(this).attr("href",currHref);
        }else{
            if (currHref.charAt(currHref.length - 1) === '?')                           
                $(this).attr("href",currHref);
            elseif (currHref.indexOf('?') > 0)                
                $(this).attr("href",currHref+"&rand="+getRandom());
            else                  
                $(this).attr("href",currHref+"?rand="+getRandom());
        }
   });               
});
functiongetRandom(){
    var randomnumber = Math.floor(Math.random()*10000); 
    return randomnumber;
}

Post a Comment for "Add Parameter To Links On Page Using Jquery"