0

So I have this url: /somepage/goes-here/something?image=main_image.jpg&type=shirt

How do I get out the two different attributes to then apply an eventListener to them?

I've tried the following:

var originalUrl = window.location.href
var type = originalUrl.search.get("type");
var image = originalUrl.search.get("image");

But I don't really think I'm getting the attributes with .search.get. Plus it errors with .search.get("type") is not a function.

I've also tried the following:

function getParam(param){
return new URLSearchParams(window.location.search).get(type);
}

I'm honestly not too familiar with URLSearchParams but wouldn't it be similar to above? How would I get both params here?

I also have for jQuery, which I'm not familiar with, the following:

$(function(){
$.url.attr('image')
$.url.attr('type')
});

This one...no idea. But it fails as it's not bringing in the url.

Jake
  • 1,328
  • 1
  • 21
  • 51
  • 1
    Why do you want to add event listeners to strings? – Andy Dec 06 '17 at 18:42
  • I don't. I want to add event listeners to buttons that are associated with the parameters. For instance the image has a container around it that I want to be made active. And the type is actually associated with a button. Based on the image and the type being present I want their associations to be made active. Step one, read through and find the parameters being passed. Step two, apply event listeners. – Jake Dec 06 '17 at 18:44
  • https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Andy Dec 06 '17 at 18:48
  • This is great stuff! Thanks. – Jake Dec 06 '17 at 19:19

1 Answers1

3

Alternatively you could construct a URL object and grab them as so:

var originalUrl = new URL(location.href);
var type = originalUrl.searchParams.get('type');
var image = originalUrl.searchParams.get('image');

One thing to note. As of this post it seems that it's not supported by IE.

Carl Edwards
  • 13,826
  • 11
  • 57
  • 119