Lincoln Mullen
Lincoln Mullen

Reputation: 6455

Using d3 with URL query strings

I'd like to be able to provide URLs to access different views of visualizations that I've created. For example, some of the visualizations change for each year or for each variable. When the user changes the year or the variable depicted, I'd like to update the URL. For example, from

index.html?year=1790&variable=population

to

index.html?year=1820&variable=populationdensity

Then, when a visitor comes to one of those URLs, to initialize the visualization using the query string.

Perhaps I'll have to write this myself, but has anyone done something similar or have sample code for how to do this?

Upvotes: 3

Views: 1941

Answers (1)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

on your script you can do something like

var i=0;
var telem;
var search_values=location.search.replace('\?','').split('&');
var query={}
for(i=0;i<search_values.length;i++){
    telem=search_values[i].split('=');
    query[telem[0]]=telem[1];
}

console.log(query);

after this the query variable should hold all the key:values of your query string. this of should be contained inside a function to avoid polluting the global scope

Upvotes: 2

Related Questions