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.

4
  • 1
    Why do you want to add event listeners to strings? Commented Dec 6, 2017 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. Commented Dec 6, 2017 at 18:44
  • stackoverflow.com/questions/901115/… Commented Dec 6, 2017 at 18:48
  • This is great stuff! Thanks. Commented Dec 6, 2017 at 19:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using searchParams.get('type') would I get shirt?
If your url was something like http://example.com/?type=shirt I would assume so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.