0

To start, I am a complete beginner to Javascript and any language for that matter. I am using wordpress for my website.

I have a website that has images loaded according to a query string.

Ex.

www.mysite.com/page1                       no image
www.mysite.com/page1?sponsor=calbest       logo of calbest
www.mysite.com/page1?sponsor=pfcu          logo of pfcu

My question is: how can I keep the current query string even when visiting other pages?

For example, I start off at www.mysite.com/page1?sponsor=calbest and want to click a link to another page. How can I ensure that I arrive at www.mysite.com/page2?sponsor=calbest without having to write it directly in HTML?

The reason I need this is so that I can update page1 or others and add various sponsors to the pages so they have a "personalized" webpage.

Is there a Javascript function that could just add the query string in use to any link I click?

ajcsilva
  • 23
  • 1
  • 4

1 Answers1

0

This is a "Jquery" way to do it:

<html>
 <head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
  <script type='text/javascript'>

   $(function(){
    getParameterByName = function(name) {
       name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
       var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
           results = regex.exec(location.search);
     return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    var sponsor = getParameterByName('sponsor') || 'calbest';
    $('a.sponsor').each(function( index ) {
      $(this).attr("href", $(this).attr("href")+ "?sponsor="+ sponsor);
    });
  });
  </script>
 </head>
 <body>
   <a class="sponsor" href="http://www.google.com">Google</a>
   <a class="sponsor" href="http://www.yahoo.com">Yahoo</a>
   <a class="sponsor" href="http://stackoverflow.com">Stackoverflow</a>
   <a  href="http://www.microsoft.com">MS Not Sponsored</a>
 </body>
</html>

Not forgetting where I got the getParameterByName

Community
  • 1
  • 1
CodeHacker
  • 2,127
  • 1
  • 22
  • 35
  • Great this worked for me. Only problem is that I had anchor tags ('#') and they don't work now as the query string is repeated after the tag. Any way around this? Thanks. – ajcsilva Jan 23 '14 at 01:19
  • well here I went for all anchors but you could for example add a specific class to the anchors you want to replace and then do something like $('a.specific_class').each(..... – CodeHacker Jan 23 '14 at 01:59