2

I have menu with different classes and one of them is photos, for photos button and for photos page. When you click on the button photos you get in url /index.php?t=photos What is the best way to find that ?t=photos with javascript or jquery and then do something if url contains this.

I tried :

if (window.location.href.indexOf("?t=photos") >= 0) {
    $('.photos').css("border-color" , "#B40404");
}

UPDATE:

I did it like this:

var requestUrl = window.location.search.toString();


if (requestUrl.indexOf('&t=photos') > -1) {
  $('.photos').css("border-color","#B40404");
}
  • 2
    Please read the following question: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Willian Jul 09 '16 at 13:26

4 Answers4

0

This should work.

var querystring = location.search;
if(querystring.indexOf('t=photos') >= 0){
  $('.photos').css("border-color","#B40404");
}
Sajan
  • 1,893
  • 2
  • 19
  • 39
0

Try this:

$.urlParam = function(name, url) {
    if (!url) {
     url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) { 
        return undefined;
    }
    return results[1] || undefined;
}

And use it like this:

if ($.urlParam('t') == 'photos')
    $('.photos').css("border-color","#B40404");

Look at this for more info https://stackoverflow.com/a/2480180/1766014

Community
  • 1
  • 1
AhmadReza Payan
  • 2,171
  • 1
  • 23
  • 33
0

You can use URI.js (https://medialize.github.io/URI.js/) library in your code for this purposes and stay assured that your code will works in all browsers

So this piece:

var uri = new URI("http://example.com/index.php?t=photos");
uri.search(true);

will return JSON: {"t": "photos"} And you can test has "t" equal "photos" or not.

Yan Pak
  • 1,767
  • 2
  • 19
  • 15
-2
var requestUrl = window.location.search.toString();

if (requestUrl != '') {
    //window.location.search returns the part of the URL 
    //that follows the ? symbol, including the ? symbol
    requestUrl = requestUrl.substring(1);

    var queryStringColl = new Array();

    //Get key:value pairs from querystring
    var kvPairs = requestUrl.split('&');

    for (var i = 0; i < kvPairs.length; i++) {
        var kvPair = kvPairs[i].split('=');
        queryStringColl[kvPair[0]] = kvPair[1];
    }
}

Check: http://dotnetprof.blogspot.in/2012/11/get-querystring-values-using-javascript.html

Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32
  • 1
    "Here, a chunk of code. Figure out what I did. Oh, by the way, read this external page for a description" ;) – Wes Foster Jul 09 '16 at 13:31
  • So you suggest copy pasting whole thing here again if I have already posted it somewhere else? ;) Even if you do, I won't consider it. If there's better suggestion, please let me know. – Nikhil Vartak Jul 09 '16 at 13:33