jeffkee
jeffkee

Reputation: 5238

Using jQuery to append URL with anchor #

While retrieving items via AJAX etc., the links are set to do this:

$(this).click(function(){
ajax_function(); // hypothetical ajax call that puts data into a <div> of my choice
return false;
});

In this scenario, I'm wondering what the best way is to utilize jQuery to add things to my URL in this format:

http://www.mydomain.com/products

turns into

http://www.mydamain.com/products#category-12,page-4

Further note- I'm talking about the actual URL of the browser (in the URL bar) not a URL that is part of the DOM.

Upvotes: 1

Views: 2692

Answers (2)

jeffkee
jeffkee

Reputation: 5238

After searching some more (with better keywords than before on Google) I found the answers I needed, and I wrote the following functions:

    function get_url_hash(argument) {
    var hash = location.hash.replace('#','');
    if(argument=='' || argument==undefined) {
        return hash;
        alert(blank);
    } else {
        var foundhash = false;
        // specific argument given - let's find the value attached. 
        var hashblock = hash.split(',');
        for(x in hashblock) {
            var hasharray = hashblock[x].split('-');
            if(hasharray[0]==argument) {
                return hasharray[1];
                foundhash = true;
            }
        }
        if(foundhash==false) {
            return false;
        }
    }
}

function modify_url_hash(argument, value) {
    // This function goes through the entire hash,
    // figures out which parts of the hash should be added, updated or removed based on entry, 
    // and then spits out final result. 
    var hash = get_url_hash();
    var foundhash = false; // foundhash is set to false by default. if this hash is NOT found, then we add it at the end! 
    var hashcount = 0; // keep count of total # so as to determine where to put the commas etc. 
    var newhash = '';
    if(hash.length>0) {
        var hashblock = hash.split(',');
        for(x in hashblock) {
            var hasharray = hashblock[x].split('-');
            if(hasharray[0]==argument) {
                hasharray[1] = value;
                foundhash = true;
            }

            if(hasharray[1]!=false && hasharray[1]!='') { // if new value is NOT false, we keep it in.. otherwise don't feed it to newhas so it disappears.
                if(hashcount>0) { newhash = newhash+','; }
                newhash = newhash+hasharray[0]+'-'+hasharray[1];
                hashcount++;
            }

        }
    }

    if(foundhash==false) {
        // this is a new hash block. 
        if(hashcount>0) { newhash = newhash+','; }
        newhash = newhash+argument+'-'+value;
    }
    location.hash = newhash;
}

Upvotes: 1

Starx
Starx

Reputation: 78961

May be something like

oldlink = $('#mylinkselector').attr("href");
newlink = oldlink="#category-12,page-4";
$("#mylinkselector").prop("href",newlink);

Upvotes: 1

Related Questions