0

I want to change the css of a div depending on the url you are at.

Here is the code I came up with...

<script>
if (window.location.href == "http://www.example.com/?tab-1") {
    function(){ 
        $('body').css('color','red !important');
    }
}
</script>

Could someone explain how properly execute a function based on the current url?

Thank you.

2
  • 2
    stackoverflow.com/questions/6076576/… Commented Sep 9, 2013 at 23:37
  • But you're not executing the function... Commented Sep 9, 2013 at 23:38

3 Answers 3

0

To execute a different function based on what comes after the question mark on a url (taking the question at face value) you can use this:

var functions = {
    "tab-1": function() {
        //do tab-1 stuff
    },

    "tab-2": function() {
        //do tab-2 stuff
    }
}

$(function() {
    var qs = location.search;
    if (qs.length > 0) {
        var func = functions[qs.substring(1)]
        if ($.isFunction(func)) func();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0
$(function(){

    var tab = window.location.href.split('?')[1]; // tab-1
    if(tab){
      $('body').addClass( tab );
    }

});

than in your CSS:

.tab-1{
   background: red ;  /* add !important if needed */
}
.tab-2{
   background: blue ; /* add !important if needed */
}

demo concept

Comments

-1

You should call window.onload so that you catch the url when its entered and trigger the action that you want (in this case a css change) inmediately.

function changecss() {
    if (window.location.href == "http://www.example.com/?tab-1") {
        function(){ 
            $('body').css('color','red !important');
        }
    }

}

window.onload = changecss;

Comments

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.