Question

Detect screen resolution and load image

Asked by: cpalmer116

I need to find a piece of javascript that will allow me to detect screen resolution and then automatically load image(s) of the correct size. I don't want to create multiple versions of the same page for different browsers, because in fact my HTML and CSS build means that all my pages resize automatically to the browser - except for the images. I don't write Javascript, but I sort of feel there should be something out there that detects the screen resolution and then tells whatever it is to go and pick the small, medium or large resolution image for that screen size?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-09-17 at 05:53:05ID22832949
Tags

detect

,

resolution

,

screen

,

image

Topics

Cascading Style Sheets (CSS)

,

JavaScript

,

Extensible HTML (XHTML)

Participating Experts
4
Points
500
Comments
27

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. detect and resize webpage to clients screen resolution
    is there a way to detect the clients screen resolution and resize webpage to clients screen resolution. thanks
  2. Screen Resolution detection and Automatic Resizing
    Ok, I have found scripts which are able to detect a user's screen resolution and based on that either redirect them to a new location or else they are given a alert which states that the website is best viewed in such and such resolution. I do not want either, what I want is...
  3. Auto Resize IFRAME - CSS
    I want to auto resize an IFRAME that contains a page from a different domain. I do have control over both the parent and the child pages - on both the domains..Can you please suggest the CSS for doing this? or any other way of doing it? Thanks!

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mplungjanPosted on 2007-09-17 at 05:57:15ID: 19904460

<script>
var img = "enormous.jpg"
if (window.width<800) img ="small.jpg";
else if (window.width<1024) img ="medium.jpg";
else if (window.width<1280) img ="large.jpg";
document.write('<img src="'+img+'">')
</script>
<noscript>
<img src="medium.jpg">
</noscript>

 

by: mplungjanPosted on 2007-09-17 at 05:59:25ID: 19904472

Let me know if you need explanation

 

by: cezarFPosted on 2007-09-17 at 06:04:39ID: 19904504

 

by: cpalmer116Posted on 2007-09-17 at 06:09:48ID: 19904540

mplungjan I just want to check that I understand this. This section I can load into my linked js file:

var img = "enormous.jpg"
if (window.width<800) img ="small.jpg";
else if (window.width<1024) img ="medium.jpg";
else if (window.width<1280) img ="large.jpg";
document.write('<img src="'+img+'">')

And then this section I would need to put into my xhtml?

<noscript>
<img src="medium.jpg">
</noscript>

Apologies for lack of knowledge!
cpalmer

 

by: mplungjanPosted on 2007-09-17 at 06:15:44ID: 19904589

the script plus the noscript is what I would put next to each other where the image was to appear...

Alternatively:

if you in  the head have
<script src="linked.js"></script>

and in there have

function getImage() {
  var img = "enormous.jpg"
  if (window.width<800) img ="small.jpg";
  else if (window.width<1024) img ="medium.jpg";
  else if (window.width<1280) img ="large.jpg";
  return img;
}


then you can have in the page:

<script type="text/javascript"><!--
  document.write('<img src="'+getImage()+'" alt="My javascript generated image" />')
//--></script>
<noscript><img src="medium.jpg" alt="My static image for non-js users" /></noscript>


Where do you have your js file and what else does it contain?

 

by: Binary1Posted on 2007-09-17 at 06:21:26ID: 19904633

You can use screen.width and screen.height to get the width and height.

Here's a sample page with what you might want to do:

<html>
<head>
<script language="javascript">
      function getElement(elementID) {
            if(document.getElementById){
                  return document.getElementById(elementID);
            }else if(document.all){
                  return document.all[elementID];
            }else if(document.layers){
                  return document.layers[elementID];
            }
      }

      function setImage() {
            imgS = getElement("thisimage");
            if ( imgS != null ) {
                  if ( screen.width <= 640 ) {
                        imgS.src = "small.jpg";
                  } else if ( screen.width <= 1024 ) {
                        imgS.src = "medium.jpg";
                  } else {
                        imgS.src = "large.jpg";
                  }
            }
      }
</script>

</head>
<body onLoad="javascript:setImage();">
      <image id="thisimage" src="small.jpg">
</body>
</html>

 

by: Binary1Posted on 2007-09-17 at 06:28:57ID: 19904688

I noticed that you are looking at using 'document.write()' to do this. Keep in mind that IE will prevent this in some cases depending on how the browser is set up to handle active content. If the browser is set up to block active content a yellow band across the top is displayed stating that it block 'active content' from the page. In order to enable it the user would need to click on that band and select to allow the active content.

 

by: cpalmer116Posted on 2007-09-17 at 06:30:30ID: 19904707

Thank you so much for that clarification! I'll try it out now!

My javascript file is here: isa_new/js/isa.js. It is linked in the head of each page thus:
<script type="text/javascript" language="JavaScript" src="/js/isa.js";></script>

The only other thing that it contains is this:

menu_status = new Array();
function showHide(theid){
    if (document.getElementById) {
    var switch_id = document.getElementById(theid);

        if(menu_status[theid] != 'show') {
           switch_id.className = 'show';
           menu_status[theid] = 'show';
        }else{
           switch_id.className = 'hide';
           menu_status[theid] = 'hide';
        }
    }
}
 
Which, as I am sure you can tell, is what I use to control the show/hide function of the css menu. I'm not a great Javascript user for obvious reasons!
cpalmer

 

by: mplungjanPosted on 2007-09-17 at 06:33:30ID: 19904736

I use document.write to only load the image needed.

Of course one can do this somewhat simpler version:


<img name="myImage" src="medium.jpg" alt="My image" />
<script type="text/javascript"><!--
  var img2use = getImage();
  if (img2use!='medium')  document.images["myImage"].src=img2use;
//--></script>


Michel

 

by: mplungjanPosted on 2007-09-17 at 06:34:47ID: 19904746

PS: You still need

function getImage() {
  var img = "enormous.jpg"
  if (window.width<800) img ="small.jpg";
  else if (window.width<1024) img ="medium.jpg";
  else if (window.width<1280) img ="large.jpg";
  return img;
}

in your js  file

 

by: cpalmer116Posted on 2007-09-17 at 06:37:17ID: 19904761

Binary1,
Thank you for providing that solution and your note about active content. I specialise in producing sites which are fully accessiblity compliant and not very high tec at all ; minium java etc - so everything is 'right there' as it were. Which should mean that even if an image doesn't load a text explination of the image will. I have also specified the smallest image as the default image for the site.
cpalmer

 

by: mplungjanPosted on 2007-09-17 at 06:43:45ID: 19904818

I would like to know what scripts parts are blocked by active content blocking...
I do not see document.write as more blockable than image src changing...

 

by: landshipPosted on 2007-09-17 at 07:03:29ID: 19904961

To make sure it works across multiple browsers you can't just use window.width, try this

<script>
window.onload = function() {
      if (windowWidth = getBrowserWidth()) {  // Make sure width can be detected

      // Begin Image Changing
      if (windowWidth > 1280) {
            document.getElementById("IMAGE_ID").src = "PATH/TO/IMAGE_1280.jpg";
      } else if (windowWidth > 1024) {
            document.getElementById("IMAGE_ID").src = "PATH/TO/IMAGE_1024.jpg";
      } else if (windowWidth < 800) {
            document.getElementById("IMAGE_ID").src = "PATH/TO/IMAGE_800.jpg";
      } else {
            document.getElementById("IMAGE_ID").src = "PATH/TO/IMAGE_640.jpg";
      }
      // End Image Changing

      }  // End if browser width was detected
}  // End onload

function getBrowserWidth() {
      if (window.innerWidth) {
            return window.innerWidth;
      }
      else if (document.documentElement && document.documentElement.clientWidth != 0) {
            return document.documentElement.clientWidth;
      }
      else if (document.body) {
            return document.body.clientWidth;
      }
      return false;
}
</script>

Then in the body all you need is the image tag:
<img src="DEFAULT_IMAGE.jpg" id="IMAGE_ID" alt="image description" />


Change the IMAGE_ID to whatever you want, and add multiple images by giving them unique ids and repeating the section of the script with the new image id.

 

by: landshipPosted on 2007-09-17 at 07:06:00ID: 19904990

Sorry I had a > the wrong way, this line should be:

} else if (windowWidth > 800) {

 

by: mplungjanPosted on 2007-09-17 at 07:06:24ID: 19904993

Yes you can if you want to know the resolution of the screen

The resolution of the screen does not have anything to do with the size of the viewport (window)
I would not want the fontsize to become smaller just because I made the window smaller. Same for an image especially if the image has some text

Michel

 

by: mplungjanPosted on 2007-09-17 at 07:08:56ID: 19905014

and I would do
>= 1280
>= 1024

and so on

 

by: landshipPosted on 2007-09-17 at 07:12:04ID: 19905038

You're right, but the viewport (window) is what the user is looking at, so if they have any browser sidebars (or the browser is smaller than maximized) the resolution is going to be misread and the page will display the wrong size image to fit the layout.

 

by: landshipPosted on 2007-09-17 at 07:23:22ID: 19905137

If you use >= 1280 to get the window width as accurate as possible subtract about 16-20 pixels to account for the scroll bar. A 1280 monitor won't have a windowWidth of 1280 due to the scroll bar.

For testing the width you could add:
alert(windowWidth);
right before the image changing part of the code to display a pop up of what the script detects as the window width.

 

by: mplungjanPosted on 2007-09-17 at 07:53:34ID: 19905408

I do not get what you are saying....

If the resolution is 1024x768, the browser window can be 640x480 or whatever but the site can still serve page designed for 1024x768 - if the user runs with a sidebar, then I would rather turn it off than get font-sizes and images that are too small to see...

 

by: landshipPosted on 2007-09-17 at 08:50:41ID: 19905879

There is no need to turn off the script, (and you can't turn off a user's browser sidebar). The line:
      } else {
            document.getElementById("IMAGE_ID").src = "PATH/TO/IMAGE_640.jpg";
      }
sets the smallest size for the image so the image will not get any smaller than the image declared in this else statement.

The text size is determined by the user's browser and computer configuration, this script only affects the image.

cpalmer116,
Is the image text content or an image?

 

by: mplungjanPosted on 2007-09-17 at 12:00:36ID: 19907333

I meant if *I* am a user that runs with a sidebar, I'd rather turn it off than have a smaller resolution forced upon me due to the size of the window I chose to use.

 

by: cpalmer116Posted on 2007-09-18 at 02:23:29ID: 19911288

Landship,
The image is a logo; so somewhere between an image and text!
cpalmer

 

by: landshipPosted on 2007-09-18 at 07:11:50ID: 19912901

That should work fine with my assumption of what you were looking for. I just found that www.themaninblue.com has an event listener to detect when a user resizes their browser so the image could adjust along with it. Otherwise both scripts only resize the image the first time a page is loaded.

add this before the // Begin Image Changing:
attachEventListener(window, "resize", checkBrowserWidth, false);

and put this function before the </script> tag
function attachEventListener(target, eventType, functionRef, capture)
{
    if (typeof target.addEventListener != "undefined")
    {
        target.addEventListener(eventType, functionRef, capture);
    }
    else if (typeof target.attachEvent != "undefined")
    {
        target.attachEvent("on" + eventType, functionRef);
    }
    else
    {
        return false;
    }

    return true;
};

 

by: mplungjanPosted on 2007-09-18 at 07:27:44ID: 19913071

Ok, Just to recap

* my script (suggestions) looks at the resolution of the screen of the user before loading a logo - it ignores the size of the browser window
* Binary's suggestion will load a logo and change it after the page has loaded
* Landship's suggestions look at the size of the browser window - if you have a small browser window you get a small logo - The last suggestion will resize the logo when you resize the browser

 

by: landshipPosted on 2007-10-04 at 14:41:27ID: 20018128

So, cpalmer, did we answer your question or was there more you needed?

 

by: cpalmer116Posted on 2007-12-07 at 15:44:07ID: 31407857

Thank you so much for your solution! I thought I had accepted yours ages ago, but aparently not. So thank you again and apologies for the delay!
Christy Palmer

 

by: mplungjanPosted on 2007-12-09 at 01:08:30ID: 20436479

hmmm...

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...