javascriptonclick

Extracting elements of an OnClick function to modify it at runtime


Is this the best way to modify certain links in my webpage to add search parameters? Are there better ways?

I do not want to do it by Sessions variables, because I am going to another subdomain of my site.

Here is my stopgap solution on the lines @Pointy suggested:

My div is:

<div id="myDiv" loc="http://anothersubdomain.mysite.com/anotherpage.html" >
    <img src="./icons/icon.png" alt="Click Me" />
    <br />
    Click Me
</div>

My JavaScript code is:

const myChangeLoc = searchParams => baseLink => () => {window.location = baseLink + "?" + searchParams;};

AddSearchParams = function(){
    let params = Array.from(new URLSearchParams(location.search)),
        str = params.reduce((t,a) => {
            if(t.length > 0) t += "&";
            t += a[0] + "=" + a[1];
            return t;
        }, "");
    const f = myChangeLoc(str);

    $('div[loc]').each(function() {
        this.addEventListener("click", f($(this).attr('loc')));;
    });
}
AddSearchParams();

Solution

  • You don't need to parse the URLSeachParams as a string to add them. Just set the search property of each link to the one created for the current page.

    I will suggest that you create actual anchors for all the relevant links, and then use the rel attribute (HTML attribute: rel) because it has a semantic meaning in HTML.

    // for testing on SO, add parameters to the URL of this page
    const url = new URL(location);
    url.searchParams.set("q", "test");
    url.searchParams.set("p", "2");
    history.pushState({}, "", url);
    
    /* start here: create a URLSeachParams object
       with the current parameters*/
    const search = new URLSearchParams(location.search);
    
    /* loop all anchors that are defined as external
       and add the parameters from the URLSeachParams object */
    document.querySelectorAll('a[rel="external"]')
      .forEach(a => a.search = search);
    <a rel="external" href="http://anothersubdomain.mysite.com/anotherpage.html">
      <img src="./icons/icon.png" alt="Click Me" />Click Me
    </a>