Change background dependent upon arriving URL - html

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.
Live = www.myserver.com/live/index.html
Development = www.myserver.com/development/index.html
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!

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;
}

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>

Related

Prevent static files inside a CSS from being displayed before the page is loaded

I am modifying some JSP files, and every time I upload a new version, if people don't update the cache, the styles are not rendered as they should be; it is looking not good and without styles applied.
To solve this problem, I have followed an example from Stack Overflow that adds a numeric value to the CSS file, preventing it from being cached in the browser. The specific link I've seen is this one:
https://wpreset.com/force-reload-cached-css/
But I've found that whenever I press F5 or navigate to other JSP's that apply the same stylesheet, the files that are part of that CSS file are always seen just before rendering. I added a GIF with a dummy example to exhibit what I mean:
Animated GIF demonstrating the problem
How could I avoid this?
Would something like the following help?
/* CSS */
.no-js #loader { display: none; }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
|
// Js
$(window).load(function() { // Wait for window load
// Animate loader off screen
$("#loader").animate({
top: -200
}, 1500);
});
Like it is used here.
I have already been able to solve it.
In the end I have chosen to nest inside a window.onload, the document.ready like this:
window.onload = function () {
document.getElementsByTagName("html")[0].style.visibility = "visible";
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && f.href.indexOf("custom-common.css") != -1) {
var g = f.href.replace(/(&|\?)rnd=\d+/, '');
f.href = g + (g.match(/\?/) ? '&' : '?');
f.href += 'rnd=' + (new Date().valueOf());
}
}
$(document).ready(function () {
$('.main-link').click(function () {
And change the visibility of the html document. I have omitted the rest of the code, but you can get an idea. Many thanks to Robert Bradley and Adam for shedding light and helping me.

Prevent images from being downloaded to page on mobile site

How can I make it so that within the mobile version of my site the images are not downloaded to from the web server as these are large files that are not needed and not being used and therefore severely impacting the use of the mobile version of the site. Having looking at previous threads of such nature I saw that hiding the parent of the image using code such as below can benefit.
.parent {display:block;}
.background {background-image:url(myimage.png);}
#media only screen and (max-width:480px) {
.parent {display:none;}
}
The problem being I don't want to use background image CSS for SEO issues associated with them as I like to use Schema tagging etc ..so how can I prevent an IMG tag from being downloaded, as display:none; only hides the image rather than stopping it being downloaded.
Note: This is not for copyright protection issues e.g. preventing right click etc etc but for speed and ultimately size of the downloaded content to mobile.
This solution uses CSS to prevent background-images from loading and jQuery to prevent images from loading. I'm not familiar with any CSS solution that will prevent images from loading.
JS Fiddle: http://jsfiddle.net/CoryDanielson/rLKuE/6/
If you know the images height and width (or even ratio) ahead of time you could set the background-image for a bunch of fixed size DIVs. This might be applicable for icons and layout-type images. Look at the HTML/CSS below for an example of that.
Background Images
/* hidden by default */
aside {
display: none;
}
/* Pictures load for 'big screen' users.. pcs/tablets? */
#media screen and (min-width: 750px) {
aside {
display: block;
}
.catpicDiv {
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
background-image: url('http://img2.timeinc.net/health/images/slides/poodle-1-400x400.jpg');
background-size: cover;
}
}
and HTML
<aside>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
</aside>
Image Elements are a different story...
I don't know of any purely CSS solution to prevent them from loading the images. So I'd solve it like this:
Define IMG tags as follows
<img src="" data-src="url-to-image.jpg" />
Then, somewhere in the head of the document you need similar javascript
1) Function to load all of the images
function loadAllTheImages() {
$("img").each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
}
2) Code to determine if the user is on mobile or a PC (slow vs fast connection) and then load the images.
This code isn't bulletproof, there are much more accurate and reasonable tests than this.
$(window).load(function(){
if ( $(window).width() > 750 ) {
loadAllTheImages(); // !
} else {
$("body").append("<a id='mobileCheck' href='javascript: void(0);'>I GOTS 4G, LEMME HAVE EM!</a>");
}
});
3) As well as maybe some code to activate a button to load the images anyways? Why not, I guess... ?
$(document).ready(function(){
$('body').prepend("<h1>" + $(window).width().toString() + "</h1>");
$('body').on('click', '#mobileCheck', function(){
loadAllTheImages(); // !
$("#mobileCheck").remove();
});
});
Similar solution as here and what I hypothesized in the comments:
Delay image loading with jQuery
There is no native solution in CSS that would prevent images from loading even if you hide them or set display to none.
You have to use some JS to achieve that result. If you are familiar with JS that should not be an issue at all. There are several plugins ready to go to do what you want. You can also write your own JS because its not that difficult.
Here is my code that loads images based on the screen size:
DEMO AT CODE PEN
It works without any libraries like JQ but if you use one of those it will automatically switch to it (Tweak it to your specific needs).
JS
// use jQuery or pure JS
if (typeof jQuery !== 'undefined') {
// jQuery way
// alert("jquery");
$(function() {
$(window).on('load resize', function() {
var products = $("[data-product-image]");
products.each(function(key, value) {
var bg = null;
if (window.outerWidth < 500) return;
if (window.outerWidth < 1000) bg = $(value).data("product-image-s");
if (window.outerWidth >= 1000) bg = $(value).data("product-image");
console.log($(window).outerWidth);
$(value).css({
'background-image': 'url(' + bg + ')',
'background-position': 'center',
'background-size': 'cover',
});
});
});
});
} else {
// Pure JS way
// alert("JS");
(function() {
window.addEventListener('load', wlImageLoader);
window.addEventListener('resize', wlImageLoader);
function wlImageLoader() {
console.log('event! Trig trig');
var all = document.getElementsByTagName("div");
var products = [];
for (i = 0; i < all.length; i++) {
if (all[i].hasAttribute('data-product-image')) {
products.push(all[i]);
}
}
Array.prototype.forEach.call(products, function(value) {
var bg = null;
var curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
if (window.outerWidth < 500 || curent != 'none') return;
if (window.outerWidth < 1000 && curent == 'none') bg = value.getAttribute('data-product-image-s');
if (window.outerWidth >= 1000 && curent == 'none') bg = value.getAttribute('data-product-image');
// if (window.outerWidth >= 2000 && curent == null) bg = value.getAttribute('data-product-image-l');
if(bg == null || curent != 'none') return;
value.style.backgroundImage = "url(" + bg + ")";
value.style.backgroundPosition = "center";
value.style.backgroundSize = "cover";
curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
});
}
})();
}
HTML
<div data-product-image="img/something_normal.jpg" data-product-image-s="img/something_small.jpg" id="p3" class="product">
However if you are a time loading freak you probably prefer to write your code natively in JS as you often don't use most of the jQuery library. For fast internet connection this is not a problem but if you target mobile devices on country side that might make a difference.
I would suggest combining perhaps the #import and #media commands to only #import the stylesheet which contains images if the #media tag meets you criteria (say, over a certain resolution).
So by default you wouldn't import the stylesheet which applies the BG image, you'd only end up doing it if you had determined the site was 'non-mobile'..if that makes sense!
The W3c site has some decent examples of combining the rules:
http://www.w3.org/TR/css3-mediaqueries/#media0

Chrome extension used to refresh pages

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?
Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html
Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.

Lifehacker implemention of url change with Ajax

I see that Lifehacker is able to change the url while using AJAX to update part of the page. I guess that can be implemented using HTML5 or history.js plugin, but I guess lifehacker is using neither.
Does any one has a clue on how they do it?
I am new to AJAX and just managed to update part of the page using Ajax.
Thank you #Robin Anderson for a detailed step by step algo. I tried it and it is working fine. However, before I can test it on production, I would like to run by you the code that I have. Did I do everything right?
<script type="text/javascript">
var httpRequest;
var globalurl;
function makeRequest(url) {
globalurl = url;
/* my custom script that retrieves original page without formatting (just data, no templates) */
finalurl = '/content.php?fname=' + url ;
if(window.XMLHttpRequest){httpRequest=new XMLHttpRequest}else if(window.ActiveXObject){try{httpRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}
/* if no html5 support, just load the page without ajax*/
if (!(httpRequest && window.history && window.history.pushState)) {
document.href = url;
return false;
}
httpRequest.onreadystatechange = alertContents;
alert(finalurl); /* to make sure, content is being retrieved from ajax */
httpRequest.open('GET', finalurl);
httpRequest.send();
}
/* for support to back button and forward button in browser */
window.onpopstate = function(event) {
if (event.state !== null) {
document.getElementById("ajright").innerHTML = event.state.data;
} else {
document.location.href = globalurl;
return false;
};
};
/* display content in div */
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var stateObj = { data: httpRequest.responseText};
history.pushState(stateObj, "", globalurl);
document.getElementById("ajright").innerHTML = httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
PS: I do not know how to paste code in comment, so I added it here.
It is not an requirement to have the markup as HTML5 in order to use the history API in the browser even if it is an HTML5 feature.
One really quick and simple implementation of making all page transistions load with AJAX is:
Hook up all links except where rel="external" exist to the function "ChangePage"
When ChangePage is triggered, check if history API is supported in the browser.
If history API isn't supported, do either push a hashtag or make a normal full page load as fallback.
If history API is supported:
Prevent the normal link behaviour.
Push the new URL to the browser history.
Make a AJAX request to the new URL and fetch its content.
Look for your content div (or similar element) in the response, take the HTML from that and replace the HTML of the corresponding element on the current page with the new one.
This will be easy to implement, easy to manage caches and work well with Google's robots, the downside is that is isn't that "optimized" and it will be some overhead on the responses (compared to a more complex solution) when you change pages.
Will also have backward compatibility, so old browsers or "non javascript visitors" will just get normal page loads.
Interesting links on the subject
History API Compatibility in different browsers
Mozillas documentation of the History API
Edit:
Another thing worth mentioning is that you shouldn't use this together with ASP .Net Web Forms applications, will probably screw up the postback handling.
Code addition:
I have put together a small demo of this functionality which you can find here.
It simply uses HTML, Javascript (jQuery) and a tiny bit of CSS, I would probably recommend you to test it before using it. But I have checked it some in Chrome and it seems to work decent.
Some testing I would recommend is:
Test in the good browsers, Chrome and Firefox.
Test it in a legacy browser such as IE7
Test it without Javascript enabled (just install Noscript or similar to Chrome/Firefox)
Here is the javascript I used to achieve this, you can find the full source in the demo above.
/*
The arguments are:
url: The url to pull new content from
doPushState: If a new state should be pushed to the browser, true on links and false on normal state changes such as forward and back.
*/
function changePage(url, doPushState, defaultEvent)
{
if (!history.pushState) { //Compatability check
return true; //pushState isn't supported, fallback to normal page load
}
if (defaultEvent != null) {
defaultEvent.preventDefault(); //Someone passed in a default event, stop it from executing
}
if (doPushState) { //If we are supposed to push the state or not
var stateObj = { type: "custom" };
history.pushState(stateObj, "Title", url); //Push the new state to the browser
}
//Make a GET request to the url which was passed in
$.get(url, function(response) {
var newContent = $(response).find(".content"); //Find the content section of the response
var contentWrapper = $("#content-wrapper"); //Find the content-wrapper where we are supposed to change the content.
var oldContent = contentWrapper.find(".content"); //Find the old content which we should replace.
oldContent.fadeOut(300, function() { //Make a pretty fade out of the old content
oldContent.remove(); //Remove it once it is done
contentWrapper.append(newContent.hide()); //Add our new content, hidden
newContent.fadeIn(300); //Fade it in!
});
});
}
//We hook up our events in here
$(function() {
$(".generated").html(new Date().getTime()); //This is just to present that it's actually working.
//Bind all links to use our changePage function except rel="external"
$("a[rel!='external']").live("click", function (e) {
changePage($(this).attr("href"), true, e);
});
//Bind "popstate", it is the browsers back and forward
window.onpopstate = function (e) {
if (e.state != null) {
changePage(document.location, false, null);
}
}
});
The DOCTYPE has no effect on which features the page can use.
They probably use the HTML5 History API directly.

Problem with Chrome and Symfony [duplicate]

I'm trying to print iframe content.
contentWindow.focus();
contentWindow.print();
This code works in IE, Firefox and Safari. But don't work in Chrome and Opera. These browsers print entire page.
I tried to use this topic How do I print an IFrame from javascript in Safari/Chrome. But it didn't help me.
Could someone help me?
This is a known bug in Opera. In addition to the above ideas for workarounds, you may want to play with something like this:
var clone=document.documentElement.cloneNode(true)
var win=window.open('about:blank');
win.document.replaceChild(clone, win.document.documentElement);
win.print();
I have not tested this but it should create a copy of the page in a popup window and print it, without having to load the content a second time from the server or loosing any DOM modifications you may want printed.
As I understand, it's impossible to implement iframe printing without opening new window.
My print function:
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) {
var href = contentWindow.location.href;
href = href.indexOf("?") > -1 ? href + "&print=1" : href + "?print=1";
var printWindow = window.open(href, "printWindow", "scrollbars=yes");
printWindow.focus();
}
else {
contentWindow.focus();
contentWindow.print();
}
Also I added the following code to the end of the body (when print==1):
<script type='text/javascript'>
function invokePrint() {
if (document.readyState && document.readyState!='complete')
setTimeout(function() { invokePrint(); }, 50);
else if (document.body && document.body.innerHTML=='false')
setTimeout(function() { invokePrint(); }, 50);
else {
focus();
print();
}
}
invokePrint();
</script>
I cannot reproduce your problem with Chrome. Opera, however, does indeed still print the entire outer page when trying to only print the iframe.
I have devised a workaround and although it does work mostly, it is not 100% failsafe (amongst others because Opera wraps lines for printing; I don't know how to calculate the correct height in such cases). That said, the following code works at least reasonable (using jQuery for convenience):
if ($.browser.opera) {
var ifr = $('#youriframe');
var ifrbody = ifr.get(0).contentDocument.body;
var sheet = $([
'<style type="text/css" media="print">',
'body * {',
' display: none;',
'}',
'#youriframe {',
' border: none;',
' display: block;',
' height: ', ifrbody.scrollHeight, 'px;',
' margin: 0px;',
' padding: 0px;',
' width: ', ifrbody.scrollWidth, 'px;',
'}',
'<\/style>'
].join(''));
$('head').append(sheet);
window.print();
sheet.remove();
}
Hope this helps.
I tried above code and after making changes to the above codes I came with conclusive code as follows
var win=window.open('about:blank');
win.document.write('<html><head></head><body>');
win.document.write('<iframe frameBorder="0" align="center" src="'+window.location.href+'" onload="test()" style="width: 619px; height: 482px;"></iframe>');
win.document.write('<scr'+'ipt>function test(){window.focus();window.print()}</sc'+'ript></body></html>');
win.document.close();
if (window.focus) {win.focus()}
try this one