Roger W
Roger W

Reputation: 107

Change background dependent upon arriving URL

Hi and hope someone can help.

I have a live site and also a development site where I test out new code before deployment but basically they have the same content e.g.

Is there a way of setting the (say) CSS background property dependent upon the url that has been used to arrive at the site.

My current CSS =

body {
    background: #eff;
    /* change this to background: #ccc; if on development site */
    margin:25px;
}

Why? Well, I frequently find myself uploading or testing new code on the wrong site.

Not a big issue I know but useful if I could have a visual clue as to which site I'm testing.

My thanks for your interest.

Now Solved Thanks for input from @Adam Buchanan Smith, @Dekel and Mr Green. I sort of used @Dekel's logic but changed it to jQuery along the following lines:

<script>
$(document).ready(function(){
// Set background dependent upon url i.e. www.myserver.com/cab or www.myserver.com/cab2
// cab2 is the development site, cab the live site
// Also change text in div id="live" from 'Live Site' to 'Development Site' if arrives at by cab2   
    if (document.location.pathname.indexOf('cab2') > -1){
    $('body').css({"background":"#BFFFDF"});
    document.getElementById('live').innerHTML = "Development Site";
    } else {
        $('body').css({"background":"#efffff"});
        document.getElementById('live').innerHTML = "Live Site";
    }
}
</script>

My thanks to all for your interest!

Upvotes: 1

Views: 80

Answers (2)

Dekel
Dekel

Reputation: 62626

Not something you can do in pure html/css, but you can use both javascript and server side language for that.

In javascript you can check if the document.location.hostname or document.location.pathname to check the domain/url you are currently using.

In javascript for example you can use:

if (document.location.pathname.indexOf('development') > -1) {
    body = document.getElementsByTagName('body')[0]
    body.setAttribute('class', body.getAttribute('class') + ' development')
}

Using PHP you can use $_SERVER['REMOTE_HOST'] and $_SERVER['REQUEST_URI'].

if (strpos($_SERVER['REQUEST_URI'], 'development')) {
    echo "<body class=\"development\">";
} else {
    echo "<body>";
}

And in the css file you can use:

body {
    background: #eff;
}
body.development {
    background: #ccc;
}

Upvotes: 1

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9457

Theoretically something like this could work for you in just plain javascript using document.referrer;

<body onload="checkURL()">
</body>
<script>
function checkURL(){
var testPage = "www.testpage.com";
var livePage = "www.livepage.com";
var lastPage = document.referrer;

if (lastPage == livePage){
//do something here
}
else if {lastPage == testPage}
//do something else
}
else{
//umm what did you do?
}
</script>

Upvotes: 1

Related Questions